package com.ray.service;

import static org.junit.Assert.assertNotNull;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.PrimitiveIterator.OfDouble;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.ibatis.javassist.compiler.ast.NewExpr;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Ignore;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.context.ContextLoaderListener;

import com.alibaba.druid.sql.visitor.functions.If;
import com.google.appengine.api.search.query.ExpressionParser.negation_return;
import com.google.appengine.api.search.query.QueryParser.andOp_return;
import com.google.appengine.api.search.query.QueryParser.restriction_return;
import com.google.appengine.api.xmpp.JID;
import com.ray.bean.AdvancePurchaseBean;
import com.ray.bean.CombinationKeyBean;
import com.ray.bean.CompanyBean;
import com.ray.bean.CompanyMaterialTableBean;
import com.ray.bean.CompanyMaterialTypeBean;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.DuplicateOrderUpdateRecordBean;
import com.ray.bean.DutyBean;
import com.ray.bean.FeedOrderDetailBean;
import com.ray.bean.FeedOrderMainBean;
import com.ray.bean.FeedUseMaterialCountBean;
import com.ray.bean.HalfMaterialBean;
import com.ray.bean.MaterialBean;
import com.ray.bean.MaterialTreeBean;
import com.ray.bean.OrderBean;
import com.ray.bean.OrderBean.OrderMaterial;
import com.ray.bean.OrderColorBean;
import com.ray.bean.OrderCountBean;
import com.ray.bean.OrderDeatilBean;
import com.ray.bean.OrderInfoDetailBean;
import com.ray.bean.OrderInfoDetailSourceAndApplyBean;
import com.ray.bean.OrderReceiveViewBean;
import com.ray.bean.OtherReportDeptBean;
import com.ray.bean.OtherWarehouseBean;
import com.ray.bean.ProcessBean;
import com.ray.bean.PurchaseDetailBean;
import com.ray.bean.PurchaseOrderBean;
import com.ray.bean.PurchaseOrderDetailBean;
import com.ray.bean.QueryOrderBean;
import com.ray.bean.QueryOrderPageBean;
import com.ray.bean.QueryPurchaseBean;
import com.ray.bean.ReportBean;
import com.ray.bean.UserBean;
import com.ray.bean.WarehouseInOutDetailBean;
import com.ray.bean.WorkshopMaterialStockCountBean;
import com.ray.bean.WorkshopProductionCycleBean;
import com.ray.exception.ServiceException;
import com.ray.mapper.AdvancePurchaseMapepr;
import com.ray.mapper.ApprovalMapper;
import com.ray.mapper.BasicDataMapper;
import com.ray.mapper.CompanyMapper;
import com.ray.mapper.CompanyMaterialMapper;
import com.ray.mapper.DingTalkMapper;
import com.ray.mapper.FeedUseMaterialCountMapper;
import com.ray.mapper.OrderMapper;
import com.ray.mapper.OtherWarehouseMapper;
import com.ray.mapper.PurchaseOrderMapper;
import com.ray.mapper.WarehouseMapper;
import com.ray.pojo.EquipmentRecordPojo;
import com.ray.pojo.FeedOrderDetailPojo;
import com.ray.pojo.PurchaseOrderDetailPojo;
import com.ray.util.RedirectUrlUtil;
import com.ray.util.ReturnStringUtil;
import com.ray.util.StringUtil;
import com.ray.util.TimeAndUnix;
import com.ray.util.WeiXinParamesUtil;
import com.ray.util.redis.RedisCache;
import com.ray.util.redis.RedisKey;
import com.ray.util.weixin.WeixinTemplateList;
import com.ray.util.weixin.WeixinTemplateSender;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import test.resources.service.BaseServiceTest;

@Service
public class OrderService {

	@Autowired
	OrderMapper orderMapper;
	@Autowired
	WorkshopService workshopService;
	@Autowired
	ApprovalService approvalService;
	@Autowired
	UserService userService;
	@Autowired
	OrderProcedureTemplateService orderProcedureTemplateService;
	@Autowired
	CompanyMaterialMapper companyMaterialMapper;
	@Autowired
	BasicDataMapper basicDataMapper;
	@Autowired
	ExpectDateService expectDateService;
	@Autowired
	WeiXinService weiXinService;
	@Autowired
	WeiXinPeopleService weiXinPeopleService;
	@Autowired
	CompanyMaterialService companyMaterialService;
	@Autowired
	BasicDataService basicDataService;
	@Autowired
	OtherWarehouseMapper otherWarehouseMapper;
	@Autowired
	FeedUseMaterialCountMapper feedUseMaterialCountMapper;
	@Autowired
	DingTalkMapper dingTalkMapper;
	@Autowired
	ProductionUnitFeedService productionUnitFeedService;
	@Autowired
	QueryOrderService queryOrderService;
	@Autowired
	StructureTreeService structureTreeService;
	@Autowired
	ApprovalMapper approvalMapper;
	@Autowired
	CompanyMapper compangMapper;
	@Autowired
	AdvancePurchaseMapepr advancePurchaseMapepr;
	@Autowired
	WeChatToMessageService weChatToMessageService;
	@Autowired
	PurchaseOrderService purchaseOrderService;
	@Autowired
	CompanyMaterialTypeService companyMaterialTypeService;
	@Autowired
	WarehouseMapper warehouseMapper;
	@Autowired
	PurchaseOrderMapper purchaseOrderMapper;
	@Autowired
	DuplicateOrderUpdateRecordsService duplicateOrderUpdateRecordsService;
	@Autowired
	CompanyMapper companyMapper;
	@Autowired
	PutOutServiceNew putOutServiceNew;
	@Autowired
	IssueNoteService issueNoteService;
	@Autowired
	CompanyService companyService;
	
	
	public static Set<String> reportCompanySet =new HashSet<String>();
	static {
		reportCompanySet.add("温州钲翔眼镜有限公司");
		reportCompanySet.add("方氏板材二线");
		reportCompanySet.add("温州迪诺光学有限公司");
		reportCompanySet.add("温州市雅洲眼镜有限公司");
	}

	// 获取订单信息
	public List<OrderBean> getOrderDetail(Map map) throws ServiceException {
		List<OrderBean> orderBean = orderMapper.getOrderDetail(map);
		if (null == orderBean || orderBean.size() <= 0) {
			throw new ServiceException(ReturnStringUtil.ORDER_NOTHAVE_EXCEPTION);
		}
		return orderBean;
	}

	// 获取色号 修改明细 添加加工对象参数    半架修改
	//orderId(订单编号) machining(加工对象文本)  reportMachining(报工对象) isAllMaterial(是否是交接工序) machiningValue(加工对象值) workshopNameValue(车间id) procedureVal (工序id) procedureText(工序名称) 
	public List<OrderColorBean> getColor(String orderId, String machining, String company, String reportMachining,
			int isAllMaterial, String machiningValue, String workshopNameValue, String procedureVal, String procedureText) {
		Map companyMap=new HashMap();
		companyMap.put("loginCompany", company);
		CompanyBean companyBean=companyService.getCompany(companyMap);
		List<OrderColorBean> returnList=null;
		//如果是单物料
		if(machiningValue.equals(machining)) {
			returnList=orderMapper.getOrderOneReportMaterialColor(orderId,machining,reportMachining,isAllMaterial);
		}else if("-1".equals(machiningValue)){//如果是整架
			returnList=orderMapper.getOrderAllReportMaterialColor(orderId,reportMachining);
			//如果公司不限制物料必须要到齐
			if(companyBean.getIsLimitMaterialNeedAll()==0 && !"交接入库".equals(procedureText)) {
				//将本车间没有的物料移除
				returnList=this.notListMaterialMaterial(orderId,workshopNameValue,returnList);
			}
		}else if("-2".equals(machiningValue)){//如果是车间全部
			returnList=orderMapper.getWorkShopAllReportMaterial(orderId,reportMachining);
			//将本车间没有的物料移除
			returnList=this.notListMaterialMaterial(orderId,workshopNameValue,returnList);
		}else {//否则是普通整报
			returnList=orderMapper.getOrderHalfMaterial(orderId,machiningValue,reportMachining);
			//如果公司不限制物料必须要到齐
			if(companyBean.getIsLimitMaterialNeedAll()==0 && !"交接入库".equals(procedureText)) {
				//将本车间没有的物料移除
				returnList=this.notListMaterialMaterial(orderId,workshopNameValue,returnList);
			}
		}
		returnList=orderMapper.getOrderColorMaterialAleradyReport(returnList,procedureVal,orderId);
		List<ReportBean> workAdditionalMaterialTypeList=orderMapper.getWorkAdditionalMaterialTypeList(orderId,workshopNameValue);
		//如果有附加电镀色
		if(null!=workAdditionalMaterialTypeList && workAdditionalMaterialTypeList.size() >0) {
			Map map=new HashMap();
			map.put("orderId", orderId);
			List<OrderInfoDetailBean> dianDuColor=putOutServiceNew.getDianDuInfo(map);
			for(ReportBean pp:workAdditionalMaterialTypeList) {
				for(OrderColorBean color:returnList) {
					if(pp.getMachining().equals(color.getMachining())) {
						List<OrderInfoDetailBean> additionalList=dianDuColor.stream().filter(dd->dd.getMaterialType().equals(pp.getAdditionalMaterialType())).collect(Collectors.toList());
						color.setAdditionalMaterialTypeList(additionalList);
						break;
					}
				}
			}
		}
		Collections.sort(returnList, Comparator.comparing(OrderColorBean::getRowIndex));
		return returnList;
	}

	/**
	 * 只报本车间已有的物料
	 * @param orderId
	 * @param workshopNameValue
	 * @param returnList 
	 * @return
	 */
	private List<OrderColorBean> notListMaterialMaterial(String orderId, String workshopNameValue, List<OrderColorBean> returnList) {
       	if(returnList==null || returnList.size() <= 0 ) {
       		return new ArrayList<OrderColorBean>();
       	}	
       	List<OrderColorBean> workShopHaveMaterialList=orderMapper.getWorkShopAllMaterial(orderId, workshopNameValue);
       	workShopHaveMaterialList=workShopHaveMaterialList==null?new ArrayList<OrderColorBean>():workShopHaveMaterialList;
       	Set<String> orderDetailStrSet=workShopHaveMaterialList.stream().map(OrderColorBean::getOrderDetailStr).collect(Collectors.toSet());
       	returnList=returnList.stream().filter(object->orderDetailStrSet.contains(object.getOrderDetailStr())).collect(Collectors.toList());
		return returnList;
	}

	// //获取订单生产情况（订单查询）
	// public List<Map> getOrderWork(Map mapParam) throws ServiceException {
	// return null;
	// }
	public List<Map> getOrderWork(Map mapParam) throws ServiceException {
		Set<String> allSet = new HashSet<String>();
		List<DutyBean> dutyBeanList = orderMapper.getOrderWork(mapParam);// 得到所有订单报工数据
		Map<String, List<String>> orderListMap = new HashMap<String, List<String>>();
		if (dutyBeanList.size() <= 0) {
			throw new ServiceException(ReturnStringUtil.ORDER_NOTSTART_EXCEPTION);
		}
		List<String> workShopList = workshopService.getWorkshopName(mapParam);// 得到车间名称
		orderListMap.put("order", workShopList);
		List<Map> xx = new ArrayList<Map>();// 最终整理后的数据
		xx.add(orderListMap);
		for (DutyBean dutyBean : dutyBeanList) {// 遍历得到所有订单
			allSet.add(dutyBean.getOrderId());
		}
		for (String str : allSet) {// 遍历所有订单
			Map<String, List<DutyBean>> map = new HashMap<String, List<DutyBean>>();// 用于存当前车间报工数据
			for (String workShop : workShopList) {// 遍历所有车间
				List<DutyBean> listDuty = new ArrayList();// 一个车间一个list
				for (DutyBean dutyBean : dutyBeanList) {// 遍历所有数据
					// 如果订单号与车间名称符合则存入数据
					if (dutyBean.getOrderId().equals(str) && dutyBean.getWorkShopName().equals(workShop)) {
						listDuty.add(dutyBean);
					}
				}
				map.put(workShop, listDuty);
			}
			xx.add(map);
		}
		return xx;
	}

	// 获取订单数
	public long getOrderFieeding(ReportBean reportBean) {
		return orderMapper.getOrderFieeding(reportBean);
	}

	// 获取每个框色订单数
	public List<OrderBean> getColorCount(String orderId) throws ServiceException {
		List<OrderBean> listOrder = orderMapper.getColorCount(orderId);
		return listOrder;
	}

	// 设置可短数
	public void setDuanChu(Map map) {
		String stringDate = map.get("stringDate").toString();
		JSONArray jsonArray = JSONArray.fromObject(stringDate);// 把String转换为 数组
		List<OrderBean> list = (List<OrderBean>) JSONArray.toCollection(jsonArray, OrderBean.class);
		this.checkOrderIsFinish(list.get(0).getOrderId());
		map.put("list", list);
		orderMapper.setDuanChu(map);
	}

	public OrderBean getOrderByOrderId(String orderId) {
		return orderMapper.getOrderByOrderId(orderId);
	}

	/**
	 * 获取订单物料车间工序物料类型
	 * @param procedureText (工序id)
	 * @param orderId(订单编号)
	 * @param workshopName(车间id)
	 * @param company(公司)
	 * @param procedureName(工序名称)
	 * @return
	 */
//	public List<String> getOrderMeType(String orderId, String workshopName, String company, int isAllMaterial,
//			String procedureId, String procedureText) {
//		
//		
//		List<String> returnList = new ArrayList<String>();// 实际返回的加工对象
//		List<MaterialTreeBean> orderTypeList = orderMapper.getOrderMeType(orderId, company, isAllMaterial); // 订单中的加工对象
//		if (orderTypeList == null || orderTypeList.size() <= 0) {
//			returnList.add("此订单没有可报工对象");
//			return returnList;
//		}
//
//		// 如果是交接工序,返回所有订单物料类型
//		if (isAllMaterial == 1) {
//			return orderTypeList.stream().map(MaterialTreeBean::getMaterialType).collect(Collectors.toList());
//		} else {// 如果不是
//			ProcessBean processBean = basicDataService.getProcessById(procedureId);
//			if(processBean.getProcessingObject().indexOf("款")!=-1) {
//				returnList.add("款");
//				return returnList;
//			}
//			
//			Set<String> treeTypeSet=orderTypeList.stream().map(MaterialTreeBean::getMaterialType).collect(Collectors.toSet());
//			String [] processObvjets=processBean.getProcessingObject().split(",");
//			for(int i=0;i<processObvjets.length;i++) {
//				if(treeTypeSet.contains(processObvjets[i])) {
//					returnList.add(processObvjets[i]);
//					break;
//				}
//			}
//			
//			if (returnList.size() <= 0) {
//			    returnList.add("工序加工对象与订单物料不匹配,或物料设置不报功");
//			}
//		}
//		return returnList;
//	}
	
	
	public List<MaterialTreeBean> getOrderMeType(String orderId, String workshopName, String company, int isAllMaterial,
			String procedureId, String procedureText) {
		List<MaterialTreeBean> materialTreeBeans=new ArrayList<MaterialTreeBean>();
		Map map=new HashMap<>();
		map.put("loginCompany", company);
		//获取设置半架
		List<HalfMaterialBean> halfMaterialList=structureTreeService.getHalfMaterialTypeList(map);
		if(null==halfMaterialList) {
			halfMaterialList=new ArrayList<HalfMaterialBean>();
		}
		Map<String,List<HalfMaterialBean>> halfMap=halfMaterialList.stream().collect(Collectors.groupingBy(HalfMaterialBean::getNameId));
		//如果是交接入库，匹配订单所有物料
		if("交接入库".equals(procedureText)) {
			List<MaterialTreeBean> orderTypeList = orderMapper.getOrderMeType(orderId, company, isAllMaterial); // 订单中的加工对象
			if(null==orderTypeList || orderTypeList.size()<=0) {
				MaterialTreeBean materialTreeBean=new MaterialTreeBean();
				materialTreeBean.setId("该订单无报工物料");
				materialTreeBean.setMaterialType("该车间无入库物料");
				materialTreeBeans.add(materialTreeBean);
				return  materialTreeBeans;
			}
			//设置半架
			materialTreeBeans=this.setReportMaterial(orderTypeList,halfMap,materialTreeBeans);
			materialTreeBeans.addAll(orderTypeList);
		}else if("交接出库".equals(procedureText)){
			List<MaterialTreeBean> workShopAleradyReportMaterialList = orderMapper.getWorkShopAleradyReportMaterialList(orderId, workshopName); // 车间已报工物料
			if(null==workShopAleradyReportMaterialList || workShopAleradyReportMaterialList.size()<=0) {
				MaterialTreeBean materialTreeBean=new MaterialTreeBean();
				materialTreeBean.setId("该车间无入库物料");
				materialTreeBean.setMaterialType("该车间无入库物料");
				materialTreeBeans.add(materialTreeBean);
				return  materialTreeBeans;
			}
			//设置半架
			materialTreeBeans=this.setReportMaterial(workShopAleradyReportMaterialList,halfMap,materialTreeBeans);
			List<MaterialTreeBean> mm=workShopAleradyReportMaterialList.stream().filter(pp->"0".equals(pp.getId())).collect(Collectors.toList());
			materialTreeBeans.addAll(mm);
		}else {
			List<MaterialTreeBean> orderTypeList = orderMapper.getOrderMeType(orderId, company, isAllMaterial); // 订单中的加工对象
			ProcessBean processBean = basicDataService.getProcessById(procedureId);
			if(processBean.getProcessingObject().indexOf("款")!=-1) {
				MaterialTreeBean materialTreeBean=new MaterialTreeBean();
				materialTreeBean.setId("款");
				materialTreeBean.setMaterialType("款");
				materialTreeBeans.add(materialTreeBean);
			}
			
			//如果是钲翔
			
			if(reportCompanySet.contains(company)) {
				String aleradyReportMaterial=orderMapper.getOrderAleradyReportMaterial(orderId,procedureId);
				if(null!=aleradyReportMaterial && !"".equals(aleradyReportMaterial)) {
					MaterialTreeBean materialTreeBean=new MaterialTreeBean();
					materialTreeBean.setId(aleradyReportMaterial);
					materialTreeBean.setMaterialType(aleradyReportMaterial);
					materialTreeBeans.add(materialTreeBean);
					return materialTreeBeans;
				}else {
					return orderTypeList;
				}
			}
			
			Set<String> treeTypeSet=orderTypeList.stream().map(MaterialTreeBean::getMaterialType).collect(Collectors.toSet());
			String [] processObvjets=processBean.getProcessingObject().split(",");
			for(int i=0;i<processObvjets.length;i++) {
				if(treeTypeSet.contains(processObvjets[i])) {
					MaterialTreeBean materialTreeBean=new MaterialTreeBean();
					materialTreeBean.setId(processObvjets[i]);
					materialTreeBean.setMaterialType(processObvjets[i]);
					materialTreeBeans.add(materialTreeBean);
					if(!"温州钲翔眼镜有限公司".equals(company)) {
						break;
					}
				}
			}
			
			if (materialTreeBeans.size() <= 0) {
				MaterialTreeBean materialTreeBean=new MaterialTreeBean();
				materialTreeBean.setId("工序加工对象与订单物料不匹配,或物料设置不报功");
				materialTreeBean.setMaterialType("工序加工对象与订单物料不匹配,或物料设置不报功");
				materialTreeBeans.add(materialTreeBean);
			}
		}
		
		return materialTreeBeans;
	}

	public List<MaterialTreeBean> setReportMaterial(List<MaterialTreeBean> orderTypeList, Map<String, List<HalfMaterialBean>> halfMap, List<MaterialTreeBean> materialTreeBeans) {
		Set<String> orderMaterialSet=orderTypeList.stream().map(MaterialTreeBean::getMaterialType).collect(Collectors.toSet());
		for(String nameId:halfMap.keySet()) {
			boolean bool=false;
			List<HalfMaterialBean> oneTypeHalfMaterialTypeList=halfMap.get(nameId);
			for(HalfMaterialBean ff:oneTypeHalfMaterialTypeList) {
				//如果此半架中有订单中有的物料则返回前台
				if(orderMaterialSet.contains(ff.getMaterialType())) {
					bool=true;
					break;
				}
			}
			//如果此半架的物料在订单中都有的话，将此半架返回
			if(bool) {
				MaterialTreeBean materialTreeBean=new MaterialTreeBean();
				materialTreeBean.setId(nameId);
				materialTreeBean.setMaterialType(oneTypeHalfMaterialTypeList.get(0).getHalfMaterialName());
				materialTreeBeans.add(materialTreeBean);
			}
		}
		return materialTreeBeans;
	}

	// 通过生产订单编号获取投料单信息
	public FeedOrderMainBean getFeedOrderMainByOrderId(Map map) {
		return orderMapper.getFeedOrderMainByOrderId(map);
	}

	// 保存投料单 FeedOrderDetailBean
	public void saveFeedOrder(Map map) {
		String jsonStr = map.get("feedDetail").toString();
		FeedOrderMainBean feedOrderMainBean = new FeedOrderMainBean();
		feedOrderMainBean.setId(StringUtil.getUUID());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		JSONArray jsonArray = JSONArray.fromObject(jsonStr);
		List<FeedOrderDetailBean> listDetail = (List<FeedOrderDetailBean>) JSONArray.toCollection(jsonArray,
				FeedOrderDetailBean.class);
		for (FeedOrderDetailBean dd : listDetail) {
			dd.setFeedOrderId(feedOrderMainBean.getId());
			dd.setId(StringUtil.getUUID());
			dd.setIsBuild(0);
			dd.setIsReceiveFinish(0);
			dd.setReceiveCount(0.0);
		}
		map.put("id", feedOrderMainBean.getId());
		map.put("status", 0);
		map.put("createTime", sdf.format(new Date()));
		map.put("listDetail", listDetail);
		feedOrderMainBean = this.getFeedOrderMainByOrderId(map);
		if (null == feedOrderMainBean) {
			orderMapper.insertFeedMian(map);
			orderMapper.insertFeedDetail(map);
		} else {
			map.put("id", feedOrderMainBean.getId());
			orderMapper.updateFeedDetail(map);
		}

	}

	public DatatablesViewPageBean<FeedOrderDetailPojo> getFeedOrderData(Map map) {
		DatatablesViewPageBean<FeedOrderDetailPojo> datatablesViewPageBean = new DatatablesViewPageBean<FeedOrderDetailPojo>();
		List<FeedOrderDetailPojo> feedOrderDetailPojos = orderMapper.getFeedOrderData(map);
		int count = orderMapper.getFeedOrderDataCount(map);
		/**
		 * 处理被退回投料单已领料的逻辑 李斌
		 */
		Map<String, Object> approvalParam = new HashMap<String, Object>();
		approvalParam.put("type", "3");
		approvalParam.put("loginUserId", map.get("loginUserId"));
		approvalParam.put("loginCompany", map.get("loginCompany"));
		List<String> userIds = approvalService.getApprovalIdByLoginId(approvalParam);
		datatablesViewPageBean.setApprovalUserIds(userIds);
		for (FeedOrderDetailPojo feedOrderDetailPojo : feedOrderDetailPojos) {
			map.put("orderId", feedOrderDetailPojo.getOrderId());
			map.put("materialType", feedOrderDetailPojo.getMaterialType());
			map.put("materialCode", feedOrderDetailPojo.getMaterialCode());
			map.put("materialFactory", feedOrderDetailPojo.getMaterialFactory());
			map.put("lineNo", feedOrderDetailPojo.getQueue());
			Double returnFeedOnOutCount = this.getReturnFeedOrderOnOutWarehouseCount(map);
			BigDecimal bigNoInCount = new BigDecimal(feedOrderDetailPojo.getNotInCount().toString());
			bigNoInCount = bigNoInCount.add(new BigDecimal(returnFeedOnOutCount.toString()));
			feedOrderDetailPojo.setNotInCount(bigNoInCount.doubleValue());
		}

		datatablesViewPageBean.setiTotalDisplayRecords(count);
		datatablesViewPageBean.setiTotalRecords(count);
		datatablesViewPageBean.setReturnData(feedOrderDetailPojos);
		return datatablesViewPageBean;
	}

	// 修改投料单明细
	public void updateFeedDetail(Map map) throws ServiceException {
		String strArray = map.get("feedDetailArrayJSONStr").toString();
		JSONArray jsonArray = JSONArray.fromObject(strArray);
		List<FeedOrderDetailBean> feedDetailList = (List<FeedOrderDetailBean>) JSONArray.toCollection(jsonArray,
				FeedOrderDetailBean.class);
		map.put("listDetail", feedDetailList);
		int row = orderMapper.updateFeedDetailByStatus(map);
		if (row <= 0) {
			throw new ServiceException("修改投料单失败!");
		}
	}

	// 删除投料单
	public void deleteAllFeed(String idArray) {
		JSONArray jsonArray = JSONArray.fromObject(idArray);
		List<String> idList = jsonArray.subList(0, jsonArray.size());
		orderMapper.deleteAllFeed(idList);
	}

	// 获取需要审批的投料单
	public List<FeedOrderDetailPojo> getFeedOrderNotApprovalData(Map map) {
		map.put("type", 3);// 审批类型设为投料单审批
		List<String> approvalIdList = approvalService.getApprovalIdByLoginId(map);// 获取需要本人审批的人员
		if (approvalIdList.size() <= 0 || approvalIdList == null) {
			return null;
		}
		map.put("approvalIdList", approvalIdList);
		map.remove("loginUserId");// 不查询本人投料单
		List statusList = new ArrayList();
		statusList.add(0);// 查询状态为待审批
		map.put("statusList", statusList);
		return orderMapper.getFeedOrderData(map);
	}

	// 批量审核投料单
	public String allApprovalFeedOrder(Map map) throws ServiceException {
		String idArray = map.get("beanArray").toString();
		JSONArray jsonArray = JSONArray.fromObject(idArray);
		List<FeedOrderDetailBean> detailList = (List<FeedOrderDetailBean>) JSONArray.toCollection(jsonArray,
				FeedOrderDetailBean.class);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Map<String, Object> approvalParam = new HashMap<String, Object>();
		approvalParam.put("type", "3");
		approvalParam.put("loginUserId", map.get("loginUserId"));
		approvalParam.put("loginCompany", map.get("loginCompany"));
		map.put("id", detailList.get(0).getId());
		List<String> userIds = approvalService.getApprovalIdByLoginId(approvalParam);
		String status = "0";
		String createUserId = orderMapper.getFeedOrderCreateId(map);
		if (userIds != null && userIds.size() > 0) {
			for (String id : userIds) {
				if (id.equals(createUserId)) {
					status = "1";
					break;
				}
			}
			if (status.equals("0")) {
				throw new ServiceException("您暂无权限审核此投料单!");
			}
		} else {
			throw new ServiceException("您暂无权限审核此投料单!");
		}
		FeedOrderDetailBean feedOrderDetailBean = orderMapper.getFeedOrderDetailOneById(detailList.get(0).getId());
		map.put("feedOrderId", feedOrderDetailBean.getFeedOrderId());
		String orderId = orderMapper.getOrderIdOnFeedOrderMain(map);
		if (feedOrderDetailBean.getIsBuild().equals(1)) {
			map.put("feedDetailId", feedOrderDetailBean.getId());
			String purchaseOrderId = orderMapper.getPurchaseOrderIdByMateiralCodeAndOrderId(map);
			//throw new ServiceException("该投料单已生成采购单,请打生产订单修改单后,退回采购单 订单编号 :" + orderId);
		}
		map.put("approvalTime", sdf.format(new Date()));
		map.put("detailList", detailList);
		orderMapper.allApprovalFeedOrder(map);
		// 退回或删除,消除投料单的生产单位占用数
		if ("2".equals(map.get("status").toString()) || "3".equals(map.get("status").toString())) {
			if (feedOrderDetailBean.getProductionUnitFeedCount().doubleValue() != 0) {
				Map<String, Object> feedUseMaterialMap = new HashMap<String, Object>();
				feedUseMaterialMap.put("feedDetailId", detailList.get(0).getId());
				feedUseMaterialMap.put("loginCompany", map.get("loginCompany"));
				List<FeedUseMaterialCountBean> feedUseMaterialCountBeans = feedUseMaterialCountMapper
						.getFeedUseMaterialCountByFeedDetailId(feedUseMaterialMap);
				int deleteRow = feedUseMaterialCountMapper.deleteFeedUseMaterialById(feedUseMaterialCountBeans.get(0));
				if (deleteRow < 1) {
					throw new ServiceException("消除投料单生产单位占用数异常");
				}
			}
		}
		String message = workshopService.sendApprovalStatusMassage(Integer.parseInt(status), createUserId,
				map.get("loginUserName").toString(), "投料单", RedirectUrlUtil.feddingBill);
		return message;
	}

	// 获取采购单数据
	public List<PurchaseOrderBean> getPurchaseOrderData(Map map) {
		List<PurchaseOrderBean> list = orderMapper.getPurchaseOrderData(map);
		if (list != null && list.size() > 0) {
			map.put("deptName", "采购部");
			List<UserBean> userList = userService.getDepartmentUser(map);
			// 采购人可以是当前登录人
			UserBean userBean = new UserBean();
			userBean.setId(map.get("loginUserId").toString());
			userBean.setUserName(map.get("loginUserName").toString());
			boolean flag = false;
			for (UserBean users : userList) {
				if (users.getId().equals(userBean.getId())) {
					flag = true;
					break;
				}
			}
			if (!flag) {
				userList.add(userBean);
			}
			for (PurchaseOrderBean purchaseOrderBean : list) {
				purchaseOrderBean.setUserList(userList);
				for (PurchaseDetailBean purchaseDetailBean : purchaseOrderBean.getDetailList()) {
					CompanyMaterialTableBean companyMaterialTableBean = purchaseDetailBean
							.getCompanyMaterialTableBean();
					for (PurchaseOrderDetailBean purchaseOrderDetailBean : purchaseDetailBean.getFeedDetailList()) {
						/**
						 * 处理被退回投料单已领料的逻辑 李斌
						 */
						map.put("loginCompany", map.get("loginCompany"));
						map.put("orderId", purchaseOrderDetailBean.getOrderId());
						map.put("materialType", purchaseOrderDetailBean.getMaterialType());
						map.put("materialCode", purchaseDetailBean.getMaterialCode());
						map.put("materialFactory", purchaseOrderDetailBean.getMaterialFactory());
						map.put("lineNo", purchaseOrderDetailBean.getLineNo());
						Double returnFeedOnOutCount = this.getReturnFeedOrderOnOutWarehouseCount(map);
//						BigDecimal notInCount = new BigDecimal(companyMaterialTableBean.getNotInCount().toString());
//						notInCount = notInCount.add(new BigDecimal(returnFeedOnOutCount.toString()));
//						purchaseDetailBean.getCompanyMaterialTableBean().setNotInCount(notInCount.doubleValue());
						purchaseOrderDetailBean.setFeedOutCount(returnFeedOnOutCount);
						
						//获取本订单车间审核之后已有数量
						Map calWorkShopCount = new HashMap<>();
						calWorkShopCount.put("orderId", purchaseOrderDetailBean.getOrderId());
						calWorkShopCount.put("materialType", purchaseOrderDetailBean.getMaterialType());
						calWorkShopCount.put("rowIndex", purchaseOrderDetailBean.getLineNo());
						calWorkShopCount.put("materialCode", purchaseDetailBean.getMaterialCode());
						calWorkShopCount.put("loginCompany",map.get("loginCompany"));
						//得到在车间的数量
						Double receiveCount = 0.0;
						List<OrderReceiveViewBean> calWorkShopCountList = issueNoteService.getOrderReceiveCount(calWorkShopCount);
						if(calWorkShopCountList.size()>0) {
							receiveCount= calWorkShopCountList.get(0).getReceiveCount();
						}
						purchaseOrderDetailBean.setReceiveCount(receiveCount);
						//得到未审核数量
						Double usePurchseNotApprovelCount = 0.0;
						List<OrderReceiveViewBean> mateiralNotApprovalCountList = issueNoteService.getMaterialNotApprovalCount(calWorkShopCount);
						if(mateiralNotApprovalCountList.size()>0) {
							usePurchseNotApprovelCount=mateiralNotApprovalCountList.get(0).getUsePurchseNotApprovelCount();
						}
						purchaseOrderDetailBean.setUsePurchseNotApprovelCount(usePurchseNotApprovelCount);
					}
				}
			}
		}
		return list;
	}

	public String getPurchaseOrderOther(Map map) throws ParseException, ServiceException {
		List<PurchaseOrderBean> list = orderMapper.getPurchaseOrderData(map);
		if (list == null || list.size() < 1) {
			throw new ServiceException("投料数为空不能保存为采购单");
		}
		map.put("deptName", "采购部");
		List<UserBean> userList = userService.getDepartmentUser(map);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		// 分组,使用物料代码分组
		for (PurchaseOrderBean purchaseOrderBean : list) {
			purchaseOrderBean.setUserList(userList);
			List<PurchaseDetailBean> detailList = purchaseOrderBean.getDetailList();
			for (PurchaseDetailBean purchaseDetailBean : detailList) {
				Double materialCount = 0.0;
				Double relationCount = 0.0;
				Double notInCount = 0.0;
				Double materialUseCount = 0.0;
				if (purchaseDetailBean.getCompanyMaterialTableBean() != null) {
					// 库存数量
					materialCount = purchaseDetailBean.getCompanyMaterialTableBean().getCount();
					if (materialCount == null) {
						materialCount = 0.0;
					}
					
					/*得到未审核数量 20190703 start*/
					Double usePurchseNotApprovelCount = 0.0;
					Map calWorkShopCount = new HashMap<>();
					calWorkShopCount.put("materialCode", purchaseDetailBean.getMaterialCode());
					calWorkShopCount.put("loginCompany",map.get("loginCompany"));
					List<OrderReceiveViewBean> mateiralNotApprovalCountList = issueNoteService.getMaterialNotApprovalCount(calWorkShopCount);
					if(mateiralNotApprovalCountList.size()>0) {
						usePurchseNotApprovelCount=mateiralNotApprovalCountList.get(0).getUsePurchseNotApprovelCount();
					}
					materialCount = materialCount+usePurchseNotApprovelCount;
					/*20190703 end*/
					
					// 关联数量
					relationCount = purchaseDetailBean.getCompanyMaterialTableBean().getRelationCount();
					if (relationCount == null || relationCount < 0) {
						relationCount = 0.0;
					}
					// 未入库数量
					notInCount = purchaseDetailBean.getCompanyMaterialTableBean().getNotInCount();
					if (notInCount == null) {
						notInCount = 0.0;
					}
					// 投料单物料占用数
					materialUseCount = purchaseDetailBean.getCompanyMaterialTableBean().getMaterialUseCount();
					if (materialUseCount == null) {
						materialUseCount = 0.0;
					}
				}
				List<PurchaseOrderDetailBean> feedDetailList = purchaseDetailBean.getFeedDetailList();
				// 循环遍历feedDetailList
				BigDecimal bigMaterialCount = new BigDecimal(materialCount.toString());
				BigDecimal bigNotInCount = new BigDecimal(notInCount.toString());
				BigDecimal bigRelationCount = new BigDecimal(relationCount.toString());
				BigDecimal bigMaterialUseCount = new BigDecimal(materialUseCount.toString());
				for (int j = 0; j < feedDetailList.size(); j++) {
					PurchaseOrderDetailBean purchaseOrderDetailBean = feedDetailList.get(j);
					/**
					 * 处理被退回投料单已领料的逻辑 李斌
					 */
					paramMap.put("loginCompany", map.get("loginCompany"));
					paramMap.put("orderId", purchaseOrderDetailBean.getOrderId());
					paramMap.put("materialType", purchaseOrderDetailBean.getMaterialType());
					paramMap.put("materialCode", purchaseDetailBean.getMaterialCode());
					paramMap.put("materialFactory", purchaseOrderDetailBean.getMaterialFactory());
					paramMap.put("lineNo", purchaseOrderDetailBean.getLineNo());
					Double returnFeedOnOutCount = this.getReturnFeedOrderOnOutWarehouseCount(paramMap);
//					bigNotInCount = bigNotInCount.add(new BigDecimal(returnFeedOnOutCount.toString()));
					Double purchaseCount = purchaseOrderDetailBean.getPurchaseCount();
					// 当可领数量小于等于0时,不计算了
					//订单退回的不当公共可用来处理 2018-12-01
					BigDecimal bigFeedOutCount = new BigDecimal(returnFeedOnOutCount.toString());
					BigDecimal bigPurchaseCount = new BigDecimal(purchaseCount.toString());
					bigPurchaseCount = bigPurchaseCount.subtract(bigFeedOutCount);
					purchaseOrderDetailBean.setPurchaseCount(bigPurchaseCount.doubleValue());
					/**使用车间数量等于实际投料数则无需采购*/
					if(purchaseOrderDetailBean.getPurchaseCount().equals(purchaseOrderDetailBean.getUseFactoryCount())) {
						purchaseOrderDetailBean.setPurchaseCount(0.0);
						//break;多条的时候 错误的bug 20190609
					}
					if (bigMaterialCount.add(bigNotInCount).subtract(bigRelationCount).subtract(bigMaterialUseCount)
							.doubleValue() <= 0) {
						break;
					}
					if (bigMaterialCount.add(bigNotInCount).subtract(bigRelationCount).subtract(bigMaterialUseCount)
							.subtract(bigPurchaseCount).doubleValue() >= 0) {
						purchaseOrderDetailBean.setPurchaseCount(0.0);
						bigRelationCount = bigRelationCount.add(bigPurchaseCount);
					} else {
						bigPurchaseCount = bigPurchaseCount.subtract(bigMaterialCount.add(bigNotInCount)
								.subtract(bigRelationCount.add(bigMaterialUseCount)));
						bigRelationCount = bigRelationCount
								.add(new BigDecimal(purchaseOrderDetailBean.getPurchaseCount().toString())
										.subtract(bigPurchaseCount));
						purchaseOrderDetailBean.setPurchaseCount(bigPurchaseCount.doubleValue());
						//获取未审核数量（不含订单采购入库 库存采购入库 车间退回 投料单领料）
						
						//获取本订单车间审核之后已有数量
						Map calWorkShopCount = new HashMap<>();
						calWorkShopCount.put("orderId", purchaseOrderDetailBean.getOrderId());
						calWorkShopCount.put("materialType", purchaseOrderDetailBean.getMaterialType());
						calWorkShopCount.put("rowIndex", purchaseOrderDetailBean.getLineNo());
						calWorkShopCount.put("materialCode", purchaseDetailBean.getMaterialCode());
						calWorkShopCount.put("loginCompany",map.get("loginCompany"));
						/**
						 * 20190408
						 */
						//得到在车间的数量
						Double receiveCount = 0.0;
						List<OrderReceiveViewBean> calWorkShopCountList = issueNoteService.getOrderReceiveCount(calWorkShopCount);
						if(calWorkShopCountList.size()>0) {
							receiveCount= calWorkShopCountList.get(0).getReceiveCount();
						}
						
						if(new BigDecimal(purchaseOrderDetailBean.getPurchaseCount().toString())
								.subtract(new BigDecimal(receiveCount.toString()))
								//.subtract(new BigDecimal(usePurchseNotApprovelCount.toString())) 20190703
								.subtract(new BigDecimal(purchaseOrderDetailBean.getUseFactoryCount())).doubleValue()<0) {
							purchaseOrderDetailBean.setPurchaseCount(0.0);
						}else {
							purchaseOrderDetailBean.setPurchaseCount(new BigDecimal(purchaseOrderDetailBean.getPurchaseCount().toString())
									.subtract(new BigDecimal(receiveCount.toString()))
									//.subtract(new BigDecimal(usePurchseNotApprovelCount.toString())) 20190703
									.subtract(new BigDecimal(purchaseOrderDetailBean.getUseFactoryCount())).doubleValue());
						}
					}
				}

			}
		}
		// 调用保存方法
		return purchaseOrderService.savePurchaseOrderOther(map, list);
	}

	// 发送信息
	private void getSendData(Map<String, Object> map) {
		// 物料信息
		List<CompanyMaterialTableBean> companyMaterialTableBeans = (List<CompanyMaterialTableBean>) map
				.get("companyMaterialTableBeanList");
		// 采购单
		List<PurchaseDetailBean> purchaseDetailBeanList = (List<PurchaseDetailBean>) map.get("purchaseDetailList");
		// 采购单ids
		List<String> mainList = (List<String>) map.get("mainList");
		String date = map.get("date").toString();
		for (PurchaseDetailBean purchaseDetailBean : purchaseDetailBeanList) {
			if (purchaseDetailBean.getPrice() == null) {
				continue;
			}
			for (CompanyMaterialTableBean companyMaterialTableBean : companyMaterialTableBeans) {
				if (purchaseDetailBean.getMaterialCode().equals(companyMaterialTableBean.getMaterialCode())) {
					if (companyMaterialTableBean.getUnitPrice() == null) {
						continue;
					}
					if (companyMaterialTableBean.getUnitPrice().doubleValue() >= purchaseDetailBean.getPrice()
							.doubleValue()) {
						return;
					}
					// 溢出金额
					BigDecimal overFlowMoney = null;
					// 物料单价
					Double unitPrice = companyMaterialTableBean.getUnitPrice();
					BigDecimal materialMoney = null;
					if (unitPrice == null) {
						materialMoney = new BigDecimal("0.0");
					} else {
						materialMoney = new BigDecimal(unitPrice.toString());
					}
					// 采购单价
					BigDecimal purchasePrice = new BigDecimal(purchaseDetailBean.getPrice().toString());
					if (materialMoney.doubleValue() > 0) {
						overFlowMoney = purchasePrice.subtract(materialMoney)
								.divide(materialMoney, 2, BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal("100"));
					} else {
						overFlowMoney = purchasePrice.subtract(materialMoney)
								.divide(new BigDecimal("1"), 2, BigDecimal.ROUND_HALF_DOWN)
								.multiply(new BigDecimal("100"));
					}

					String bodyMessage = "该订单采购单的物料采购单价,高出物料表中物料单价的" + (overFlowMoney) + "%";
					Map<String, Object> purchaseUnitPriceMap = new HashMap<String, Object>();
					purchaseUnitPriceMap.put("loginCompany", map.get("loginCompany"));
					String idString = mainList.toString().substring(1, mainList.toString().length() - 1);
					String queryCondition = "#type=1&mainId=" + idString.replace(" ", "");
					String pageType = RedirectUrlUtil.queryPurchaseOrder + queryCondition;
					this.sendUnitPriceAnomaliesMsg("订单采购单价异常", bodyMessage, date, purchaseUnitPriceMap, pageType);
				}
			}
		}
	}

	// 获取订单列表
	public DatatablesViewPageBean getOrderList(Map map) {
		// TODO Auto-generated method stub
		DatatablesViewPageBean bean = new DatatablesViewPageBean();
		bean.setReturnData(orderMapper.getOrderList(map));
		int total = orderMapper.getOrderListTotal(map);
		bean.setiTotalDisplayRecords(total);
		bean.setiTotalRecords(total);
		return bean;
	}

	// 获取订单列表
	public DatatablesViewPageBean getOrderListForBusiness(Map map) {
		// TODO Auto-generated method stub
		DatatablesViewPageBean bean = new DatatablesViewPageBean();
		bean.setReturnData(orderMapper.getOrderListForBusiness(map));
		bean.setiTotalDisplayRecords(orderMapper.getOrderListTotalForBusiness(map));
		bean.setiTotalRecords(orderMapper.getOrderListTotalForBusiness(map));
		return bean;
	}

	// 获取投料单的物料数据
	public DatatablesViewPageBean<FeedOrderDetailBean> getFeedOrderMaterialDate(Map map) throws ServiceException {
		int count = 0;
		int start = 0;
		int end = 0;
		String loginDeptId = "";
		UserBean userBean = new UserBean();
		userBean.setId(map.get("loginUserId").toString());
		UserBean loginUser = userService.getUserBean(userBean);
		if (loginUser == null) {
			throw new ServiceException("登录人信息异常");
		}
		if (loginUser.getDeptName() != null) {
			loginDeptId = loginUser.getDeptName();
		}
		if (map.get("start") != null) {
			start = Integer.parseInt(map.get("start").toString());
		}
		if (map.get("length") != null) {
			end = Integer.parseInt(map.get("length").toString()) + start;
		}
		map.remove("start");
		map.remove("length");
		DatatablesViewPageBean<FeedOrderDetailBean> dtcpb = new DatatablesViewPageBean<FeedOrderDetailBean>();
		List<FeedOrderDetailBean> resultData = new ArrayList<FeedOrderDetailBean>();
		Object queryType = map.get("queryType");
		boolean isAll = false;
		if (queryType == null) {
			isAll = true;
		} else {
			if (queryType.toString().equals("material")) {
				isAll = true;
			}
		}
		// 投料单
		List<FeedOrderDetailBean> feedOrderDetailBeans = orderMapper.getFeedOrderMaterialDate(map);
		if (feedOrderDetailBeans == null || feedOrderDetailBeans.size() < 1) {
			if (!isAll) {
				throw new ServiceException("物料无库存或无该物料");
			}
		}
		// 只能返回当前登录人部门的投料单物料信息
		if (feedOrderDetailBeans != null && feedOrderDetailBeans.size() > 0) {
			for (FeedOrderDetailBean feedOrderDetailBean : feedOrderDetailBeans) {
				if (loginDeptId.equals(feedOrderDetailBean.getDeptId())) {
					resultData.add(feedOrderDetailBean);
				}
			}
		}
		// 未使用订单编号等信息查询
		if (isAll) {
			// 物料信息
			List<FeedOrderDetailBean> materialFeedDetailList = orderMapper.getCompanyMaterialTableByFeedWarehouse(map);
			// 判断公司物料中是否有符合的物料
			if (materialFeedDetailList != null && materialFeedDetailList.size() > 0) {
				// 排除投料单的
				resultData.addAll(materialFeedDetailList);
			}
			if ((feedOrderDetailBeans == null || feedOrderDetailBeans.size() < 1)
					&& (materialFeedDetailList == null || materialFeedDetailList.size() < 1)) {
				throw new ServiceException("无符合数据");
			}
		}

		if (resultData.size() < 1) {
			throw new ServiceException("您无法获取其他部门的物料信息");
		} else {
			count = resultData.size();
			if (end > count) {
				end = count;
			}
			resultData = resultData.subList(start, end);
			dtcpb.setReturnData(resultData);
			dtcpb.setiTotalDisplayRecords(count);
			dtcpb.setiTotalRecords(count);
		}
		return dtcpb;
	}

	// 获取单个投料单明细
	public FeedOrderDetailBean getFeedOrderDetailOne(String orderId, String materialCode, String loginCompany) {
		return orderMapper.getFeedOrderDetailOne(orderId, materialCode, loginCompany);
	}
	
	
	/**
	 * 订单查询页面查询明细
	 * @param timeType(查询的时间类型,1制单时间2交货日期)
	 * @param startDate(开始时间)
	 * @param date (结束时间)
	 * @param deptId(部门id)
	 * @param workShop(车间id)
	 * @param type(2 未完成 1 已完成)
	 * @param dutyStatus (拖期状态 1 拖期 2 即将拖期 )
	 * @param customerId(客户型号)
	 * @param customer (客户)
	 * @param companyOrderId (公司订单编号)
	 * @param factoryId(工厂型号)
	 * @param start(分页参数)
	 * @param length (分页参数)
	 * @param request
	 * @return
	 * @throws ParseException
	 * @throws CloneNotSupportedException 
	 */
	public Map queryOrderPageDateil(Map map) throws ParseException, CloneNotSupportedException {
		Map returnMap = new HashMap<>();
		int count = 0;
		// 忽略时间
		map = this.setOrderMainMapParam(map);
		map.put("queryOrderPageDateil", 1);
		DatatablesViewPageBean<OrderBean> dtcpb = new DatatablesViewPageBean<OrderBean>();
		// 获取查询的订单基本信息
		List<OrderBean> orderList = orderMapper.queryOrderPageDateil(map);
		// 获取此条件下的订单那总条数
		OrderCountBean orderCount = orderMapper.queryOrderPageDateilCount(map);
		count=orderCount.getCount()==null?0:orderCount.getCount();
		returnMap.put("sumOrderCount", orderCount.getSumOrderCount());
		String deptId = map.get("deptId").toString().trim();
		List<WorkshopProductionCycleBean> wpcbList = new ArrayList<WorkshopProductionCycleBean>();
		// 如果有选部门
		if (deptId != null && !deptId.equals("")) {
			wpcbList = orderMapper.getDeptWorkShopProcessingObject(map);
		} else {
			Set<String> deptSet = orderList.stream().map(OrderBean::getDeptId).collect(Collectors.toSet());
			if (deptSet != null && deptSet.size() == 1) {
				List<String> deptList = new ArrayList<String>(deptSet);
				map.put("deptId", deptList.get(0));
				wpcbList = orderMapper.getDeptWorkShopProcessingObject(map);
				deptId = deptList.get(0);
			}
		}
		returnMap.put("deptWorkShop", wpcbList);
		//订单设置车间
		List<WorkshopProductionCycleBean> orderSetNoMegerWorkShopList=null;
		//公司部门车间(含订单车间排期)
		List<WorkshopProductionCycleBean> companyNoMegerWorkShopList=null;
		//订单车间报工情况（最大时间）
		List<ReportBean> reportList=null;
		//订单车间入库情况（最小时间）
		List<ReportBean> proStrList = null;
		//订单明细详情
		List<OrderDeatilBean> detailList=null;
		//订单详情
		//如果单部门的话，需要获取校验生产状况
		if(wpcbList.size()>0) {
			//订单设置车间
			orderSetNoMegerWorkShopList=orderMapper.getOrderSetNoMegerWorkShop(orderList,map.get("workShop").toString());
			//部门车间（含排期）
			companyNoMegerWorkShopList=orderMapper.getCompanyNoMegerWorkShopId(orderList,map.get("workShop").toString());
			//订单生产情况（最小时间）
			proStrList = orderMapper.getAleradyProcedureWorkShop(orderList);
			//订单明细详情
			detailList=orderMapper.getOrderInfoDetailByOrderList(orderList);
			//订单报工情况（最大时间）
			reportList=orderMapper.getOrderReportDeatilUserMixByOrderList(orderList);
		}
		//获取所有订单详情
		Set<String> notNeedPurchaseMaterialSet=this.getCompanyNotNeePurchaseMaterialType(map);
		List<QueryOrderPageBean> allListDetail = orderMapper.getOrderInfoDetailAll(orderList);
		for (int i=0;i<orderList.size();i++ ) {
			OrderBean order = orderList.get(i);
			List<QueryOrderPageBean> listDetail = allListDetail.stream().filter(detail->detail.getOrderId().equals(order.getOrderId()) && detail.getRowIndex().equals(order.getRowIndex().toString())).collect(Collectors.toList());
			listDetail = this.getOrderInfoDetailOne(listDetail,notNeedPurchaseMaterialSet);
			if (deptId != null && !deptId.equals("")) {// 如果要查询部门信息的话
				List<WorkshopProductionCycleBean> workShopIdList=orderSetNoMegerWorkShopList.stream().filter(w->w.getOrderNo().equals(order.getOrderId())).collect(Collectors.toList());
				if(workShopIdList.size()<=0) {
					workShopIdList=companyNoMegerWorkShopList.stream().filter(w->w.getOrderNo().equals(order.getOrderId())).collect(Collectors.toList());
				}
				//订单入库情况
				List<ReportBean> proStrListOrder=proStrList.stream().filter(pp->pp.getOrderId().equals(order.getOrderId()) && pp.getRowIndex().equals(order.getRowIndex().toString())).collect(Collectors.toList());
				//订单报工情况
				List<ReportBean> reportListOrder=reportList.stream().filter(pp->pp.getOrderId().equals(order.getOrderId()) && pp.getRowIndex().equals(order.getRowIndex().toString())).collect(Collectors.toList());
				//订单明细情况
				List<OrderDeatilBean> orderDetailList=detailList.stream().filter(pp->pp.getOrderId().equals(order.getOrderId()) && pp.getRowIndex().equals(order.getRowIndex().toString())).collect(Collectors.toList());
				order.setWpcbList(this.setOrderWorkShopNew(order,workShopIdList,proStrListOrder,orderDetailList,reportListOrder,listDetail));
			} else {
				order.setWpcbList(new ArrayList<WorkshopProductionCycleBean>());
			}
			this.setInAndPurchaseStatu(order,listDetail);
		}
		dtcpb.setReturnData(orderList);
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		returnMap.put("orderList", dtcpb);
		return returnMap;
	}

	/**
	 * 设置订单采购入库状态
	 * @param order  订单信息
	 * @param listDetail 订单明细信息
	 * @return
	 */
	private void setInAndPurchaseStatu(OrderBean order, List<QueryOrderPageBean> listDetail) {
		if (listDetail == null || listDetail.size() <= 0) {//如果明细为空  则未采购未入库
			order.setInStatus(0);
			order.setPurchaseStatus(0);
		} else {
			//入库状态
			Set<Integer> inStatusSet = listDetail.stream().map(QueryOrderPageBean::getInStatus).collect(Collectors.toSet());
			//采购状态
			Set<Integer> purchaseStatusSet = listDetail.stream().map(QueryOrderPageBean::getPurchaseStatus).collect(Collectors.toSet());
			
			//如果入库状态包含部分，则为部分入库
			if(inStatusSet.contains(ReturnStringUtil.PURCHASE_IN_NOT_WHOLE) || inStatusSet.contains(ReturnStringUtil.PURCHASE_NO_BUT_REPORT_NOT_WHOLE)) {
				order.setStatus(2);
			}else if (inStatusSet.contains(ReturnStringUtil.PURCHASE_NO)){//如果包含未入库的
				if(inStatusSet.size()>1) {//并且除了未入库的还包含其他状态的，则部分入库
					order.setInStatus(2);
				}else {//只报含未入库的
					order.setInStatus(0);
				}
			}else {//否则即不包含部分也不包含未入库，则已入库
				order.setInStatus(1);
			}
			
			//如果包含未采购,但是报工不完全的
			if(purchaseStatusSet.contains(ReturnStringUtil.PURCHASE_NO_BUT_REPORT_NOT_WHOLE)) {
				order.setPurchaseStatus(2);
			}else if(purchaseStatusSet.contains(ReturnStringUtil.PURCHASE_NO)) {//如果包含未采购的
				if(purchaseStatusSet.size()>1) {
					order.setPurchaseStatus(2);
				}else {
					order.setPurchaseStatus(0);
				}
			}else {//如果不包含未采购的
				order.setPurchaseStatus(1);
			}
		}
	}

	/**
	 * 获取订单主表信息
	 * 
	 * @param timeType(查询的时间类型,1制单时间 2交货日期)
	 * @param startDate(开始时间)
	 * @param date(结束时间)
	 * @param deptId(部门id)
	 * @param workShop(车间id)
	 * @param type(2 未完成 1 已完成)
	 * @param dutyStatus(拖期状态 1 拖期 2 即将拖期 )
	 * @param customerId(客户型号)
	 * @param customer(客户)
	 * @param companyOrderId(公司订单编号)
	 * @param factoryId(工厂型号)
	 * @param start(分页参数)
	 * @param length(分页参数)
	 * @param request
	 * @return
	 * @throws ParseException
	 * @throws CloneNotSupportedException 
	 */
	public Map getOrderMain(Map map) throws ParseException, CloneNotSupportedException {
		Map returnMap = new HashMap<>();
		// 忽略时间
		map = this.setOrderMainMapParam(map);
		DatatablesViewPageBean<OrderBean> dtcpb = new DatatablesViewPageBean<OrderBean>();
		// 获取查询的订单基本信息
		List<OrderBean> orderList = orderMapper.getOrderMain(map);
		// 获取此条件下的订单总条数
//		int count= orderMapper.getOrderMainCount(map);
		OrderCountBean orderCount= orderMapper.getOrderMainCount(map);
		int count=orderCount.getCount()==null?0:orderCount.getCount();
		returnMap.put("sumOrderCount", orderCount.getSumOrderCount());
		String deptId = map.get("deptId").toString().trim();
		List<WorkshopProductionCycleBean> wpcbList = new ArrayList<WorkshopProductionCycleBean>();
		// 如果有选部门
		if (deptId != null && !deptId.equals("")) {
			wpcbList = orderMapper.getDeptWorkShopProcessingObject(map);
		} else {
			Set<String> deptSet = orderList.stream().map(OrderBean::getDeptId).collect(Collectors.toSet());
			if (deptSet != null && deptSet.size() == 1) {
				List<String> deptList = new ArrayList<String>(deptSet);
				map.put("deptId", deptList.get(0));
				wpcbList = orderMapper.getDeptWorkShopProcessingObject(map);
				deptId = deptList.get(0);
			}
		}
		//设置返回车间
		returnMap.put("deptWorkShop", wpcbList);
		//订单设置车间
		List<WorkshopProductionCycleBean> orderSetNoMegerWorkShopList=new ArrayList<WorkshopProductionCycleBean>();
		//公司部门车间(含订单车间排期)
		List<WorkshopProductionCycleBean> companyNoMegerWorkShopList=new ArrayList<WorkshopProductionCycleBean>();
		//订单车间报工情况（最大时间）
		List<ReportBean> reportList=new ArrayList<ReportBean>();
		//订单车间入库情况（最小时间）
		List<ReportBean> proStrList = new ArrayList<ReportBean>();
		//订单明细详情
		List<OrderDeatilBean> detailList=new ArrayList<OrderDeatilBean>();
		//订单详情
		//如果单部门的话，需要获取校验生产状况
		if(wpcbList.size()>0) {
			//订单设置车间
			orderSetNoMegerWorkShopList=orderMapper.getOrderSetNoMegerWorkShop(orderList,map.get("workShop").toString());
			//部门车间（含排期）
			companyNoMegerWorkShopList=orderMapper.getCompanyNoMegerWorkShopId(orderList,map.get("workShop").toString());
			//订单生产情况（最小时间）
			proStrList = orderMapper.getAleradyProcedureWorkShop(orderList);
			//订单明细详情
			detailList=orderMapper.getOrderInfoDetailByOrderList(orderList);
			//订单报工情况（最大时间）
			reportList=orderMapper.getOrderReportDeatilUserMixByOrderList(orderList);
		}
		//获取所有订单详情
		List<QueryOrderPageBean> allListDetail = orderMapper.getOrderInfoDetailAll(orderList);
		Set<String> notNeedPurchaseMaterialSet=this.getCompanyNotNeePurchaseMaterialType(map);
		for (int i=0;i<orderList.size();i++) {
			OrderBean order = orderList.get(i);
			List<QueryOrderPageBean> listDetail = allListDetail.stream().filter(detail->detail.getOrderId().equals(order.getOrderId())).collect(Collectors.toList());
			listDetail = this.getOrderInfoDetailOne(listDetail,notNeedPurchaseMaterialSet);
			if (deptId != null && !deptId.equals("")) {// 如果要查询部门信息的话
				List<WorkshopProductionCycleBean> workShopIdList=orderSetNoMegerWorkShopList.stream().filter(w->w.getOrderNo().equals(order.getOrderId())).collect(Collectors.toList());
				if(workShopIdList.size()<=0) {
					workShopIdList=companyNoMegerWorkShopList.stream().filter(w->w.getOrderNo().equals(order.getOrderId())).collect(Collectors.toList());
				}
				//订单入库情况
				List<ReportBean> proStrListOrder=proStrList.stream().filter(pp->pp.getOrderId().equals(order.getOrderId())).collect(Collectors.toList());
				//订单报工情况
				List<ReportBean> reportListOrder=reportList.stream().filter(pp->pp.getOrderId().equals(order.getOrderId())).collect(Collectors.toList());
				//订单明细情况
				List<OrderDeatilBean> orderDetailList=detailList.stream().filter(pp->pp.getOrderId().equals(order.getOrderId())).collect(Collectors.toList());
				
				order.setWpcbList(this.setOrderWorkShopNew(order,workShopIdList,proStrListOrder,orderDetailList,reportListOrder,listDetail));
			} else {
				order.setWpcbList(wpcbList);
			}
			this.setInAndPurchaseStatu(order,listDetail);
		}
		dtcpb.setReturnData(orderList);
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		returnMap.put("orderList", dtcpb);
		return returnMap;
	}


	/**
	 * 设置订单车间详情
	 * @param listDetail 
	 * @param order(订单详情)
	 * @param workShopIdList(订单车间)
	 * @param proStrList(订单入库情况)
	 * @param detailList(订单明细详情)
	 * @param reportList(报工详情)
	 * @param listDetail(物料情况)
	 * @return
	 * @throws ParseException 
	 * @throws CloneNotSupportedException 
	 */
	private List<WorkshopProductionCycleBean> setOrderWorkShopNew(OrderBean order,
			List<WorkshopProductionCycleBean> workShopIdList, List<ReportBean> proStrList,
			List<OrderDeatilBean> detailList, List<ReportBean> reportList, List<QueryOrderPageBean> listDetail) throws ParseException, CloneNotSupportedException {
		//订单原料仓物料情况
		Set<String> orderMaterialTypeSet=detailList.stream().filter(detail->detail.getMaterialFactory()==1).map(OrderDeatilBean::getMaterialType).collect(Collectors.toSet());
		//订单每行最小数情况
		List<OrderDeatilBean> orderRowMinCountList=this.getOrderRowMinCountList(detailList);
		
		// 获取订单设置的没合并的车间
		List<WorkshopProductionCycleBean> orderWorkShopList = new ArrayList<WorkshopProductionCycleBean>();
		// 如果已经开始生产，则看车间是否生产，否则不做处理（默认未生茶产）
		if (null != proStrList && proStrList.size() > 0) {
			for (int i=0;i< workShopIdList.size();i++ ) {
				WorkshopProductionCycleBean wpcb = workShopIdList.get(i);
				// //如果车间已经开始生产
				ReportBean repo = this.checkWorkShopProduction(proStrList, wpcb.getId());
				// 已经开始生产
				if (repo != null) {
					if (order.getSort() <= 0) {
						wpcb.setYuJiTime("已完成");
					} else {
						wpcb.setYuJiTime(TimeAndUnix.timeAddDay(repo.getTime(), (int) (double) wpcb.getProcessCycle()));
					}
					List<ReportBean> workShopReportList=reportList.stream().filter(pp->pp.getWorkShopName().equals(wpcb.getId())).collect(Collectors.toList());		
					// 获取订单在车间入库的物料
                    Set<String> inWorkTypeSet=	workShopReportList.stream().map(ReportBean::getMachining).collect(Collectors.toSet());		
                    wpcb.setWorkShopMaterialDetailList(this.getWorkShopMaterialInStatus(inWorkTypeSet, listDetail));
					wpcb.setIsFinish(2);// 设置未未完成
					boolean bool=this.getYuShuListMain(inWorkTypeSet,detailList,workShopReportList);
					//如果已完成了
					List<ProcessBean> processList = this.getMainProcess(workShopReportList,orderRowMinCountList,orderMaterialTypeSet);
					wpcb.setProcessList(processList);
					//如果已完成
					if(bool) {
						if(processList.size()>0 && "交接出库".equals(processList.get(0).getProcessName())) {
							wpcb.setIsFinish(1);// 设置生产完成
							wpcb.setFinishTime(processList.get(0).getCreationTime());
						}else {
							wpcb.setIsFinish(3);
						}
					}
					// 获取最后一道工序生产情况
					// 获取已经生产完成的物料条数
//					List<Integer> yuShuList = orderMapper.getYuShuList(map);
					// 如果出库的物料条数大于等于应生产的物料条数
//					if (yuShuList != null && yuShuList.size() > 0 && yuShuList.size() >= inWorkTypeSet.size()) {
//						wpcb.setIsFinish(1);// 设置生产完成
//						wpcb.setFinishTime(processList.get(0).getCreationTime());
//					}
				}
			}
		} else {
			if (order.getSort() < 0) {
				for(int i=0;i<workShopIdList.size();i++) {
					workShopIdList.get(i).setYuJiTime("已完成");
				}
			} else {
				for(int i=0;i<workShopIdList.size();i++) {
					workShopIdList.get(i).setYuJiTime("");
				}
			}
		}
		for(int i=0;i<workShopIdList.size();i++) {
			orderWorkShopList.add(workShopIdList.get(i).clone());
		}
		return orderWorkShopList;
	}

	/**
	 * 
	 * @param inWorkTypeSet(入库物料类型)
	 * @param orderDetailList(订单明细)
	 * @param workShopReportList(订单车间报工数据)
	 */
	private boolean getYuShuListMain( Set<String> inWorkTypeSet,
			List<OrderDeatilBean> orderDetailList, List<ReportBean> workShopReportList) {
		boolean bool=true;
		//报工数据根据物料分组
		Map<String,List<ReportBean>> materialTypeGroupReport=workShopReportList.stream().filter(pp->"交接入库".equals(pp.getProcedur()) ||  "交接出库".equals(pp.getProcedur()) || "交接至客户".equals(pp.getProcedur()))
				                                       .collect(Collectors.groupingBy(ReportBean::getMachining));
		//订单数据根据物料分组
		Map<String,List<OrderDeatilBean>> materialTypeGroupOrder=orderDetailList.stream().collect(Collectors.groupingBy(OrderDeatilBean::getMaterialType));
		for(String materialType:inWorkTypeSet) {
			if("款".equals(materialType)) {
				continue;
			}
			List<ReportBean> oneMaterialList=materialTypeGroupReport.get(materialType);
			if(oneMaterialList == null) {
				continue;
			}
			//入库数,出库是
//			Integer inCount=oneMaterialList.stream().filter(pp->"交接入库".equals(pp.getProcedur())).mapToInt(ReportBean::getQualified).sum();
			Integer outCount=oneMaterialList.stream().filter(pp->"交接出库".equals(pp.getProcedur()) || "交接至客户".equals(pp.getProcedur())).mapToInt(ReportBean::getQualified).sum();
		    //订单明细情况
			List<OrderDeatilBean> orderDetailCountList=materialTypeGroupOrder.get(materialType);
			orderDetailCountList=orderDetailCountList==null?new ArrayList<OrderDeatilBean>():orderDetailCountList;
			//订单数、投料数，短出数
			Integer orderCount=orderDetailCountList.stream().mapToInt(OrderDeatilBean::getOrderCount).sum();
			Integer feedCount=orderDetailCountList.stream().mapToInt(OrderDeatilBean::getFeedCount).sum();
			Integer shortCount=orderDetailCountList.stream().mapToInt(OrderDeatilBean::getShortCount).sum();
		    //如果出库数小于应出库数   或者  入库数-出库出>投料数-订单数
//			if(outCount<(orderCount-shortCount) || (inCount-outCount) >(feedCount-orderCount)) {
			//不再判断二进宫的情况
			if(outCount<(orderCount-shortCount) ) {
		    	bool=false;
		    	break;
		    }
		}
		return bool;
	}

	/**
	 * 获取订单每行最小数
	 * @param orderDetailList
	 * @return
	 */
	private List<OrderDeatilBean> getOrderRowMinCountList(List<OrderDeatilBean> orderDetailLists) {
		List<OrderDeatilBean> returnList=new ArrayList<OrderDeatilBean>();
		//只算原料仓
		List<OrderDeatilBean> orderDetailList=orderDetailLists.stream().filter(detail->detail.getMaterialFactory() ==1 && detail.getFeedCount() > 0).collect(Collectors.toList());
		Map<String, List<OrderDeatilBean>> rowGroup=orderDetailList.stream().collect(Collectors.groupingBy(OrderDeatilBean::getRowIndex));
	    for(String rowIndex:rowGroup.keySet()) {
	    	List<OrderDeatilBean> rowList=rowGroup.get(rowIndex);
	    	Collections.sort(rowList, Comparator.comparing(OrderDeatilBean::getFeedCount));
	    	returnList.add(rowList.get(0));
	    }
		return returnList;
	}

	/**
	 * 获取车间最后一道工序报工数量和时间,工序名称
	 * @param orderDetailList (订单行物料详情,每行最小数)
	 * @param orderMaterialTypeSet (原料仓物料类型)
	 * @param workShopReportList(车间报工情况)
	 * @return
	 */
	private List<ProcessBean> getMainProcess(List<ReportBean> workShopReportLists, List<OrderDeatilBean> orderDetailList, Set<String> orderMaterialTypeSet) {
		List<ProcessBean> returnList=new ArrayList<ProcessBean>();
		List<ReportBean> workShopReportList=workShopReportLists.stream().filter(pp->!"-1".equals(pp.getRowIndex())).collect(Collectors.toList());
		Collections.sort(workShopReportList, Comparator.comparing(ReportBean::getTime));
		if(workShopReportList.size()>0) {
			ProcessBean pbBean=new ProcessBean();
			Integer qualityCount=0;
			
			ReportBean reportBean=workShopReportList.get(workShopReportList.size()-1);
			//如果是交接入库,数量为入库数减出库数
			if("交接入库".equals(reportBean.getProcedur())) {
				List<ReportBean> inProcedureList=workShopReportList.stream().filter(pp->"交接入库".equals(pp.getProcedur()) && orderMaterialTypeSet.contains(pp.getMachining())).collect(Collectors.toList());
//				List<ReportBean> outProcedureList=workShopReportList.stream().filter(pp->("交接出库".equals(pp.getProcedur()) || "交接至客户".equals(pp.getProcedur())) && orderMaterialTypeSet.contains(pp.getMachining())).collect(Collectors.toList());
//				List<ReportBean> inOutList=new ArrayList<ReportBean>();
//				for(int i=0;i< inProcedureList.size();i++) {
//					ReportBean in =inProcedureList.get(i);
//					Integer outCount=0;
//					for(int j=0;j<outProcedureList.size();j++ ) {
//						ReportBean out=outProcedureList.get(j);		
//						if(out.getRowIndex().equals(in.getRowIndex()) && out.getMachining().equals(in.getMachining())) {
//							outCount=out.getQualified();
//						    break;
//						}
//					}
//					//每行每个物料周转量
//					ReportBean pp=new ReportBean();
//					pp.setQualified(in.getQualified()-outCount);
//					pp.setRowIndex(in.getRowIndex());
//					inOutList.add(pp);
//				}
				//得到单行最小的报工数
				Integer fiveCount=0;//样式五（-1）数量
				Integer noFiveCount=0;//非样式五（-1） 数量
				Map<String, List<ReportBean>> rowGroup=workShopReportList.stream().collect(Collectors.groupingBy(ReportBean::getRowIndex));
				for(String rowIndex:rowGroup.keySet()) {
					List<ReportBean> rowList=rowGroup.get(rowIndex);
					Collections.sort(rowList,Comparator.comparing(ReportBean::getQualified));
//					if("-1".equals(rowIndex)) {
//						fiveCount=rowList.get(0).getQualified();
//			    	}else 
			    	{
			    		noFiveCount=noFiveCount+rowList.get(0).getQualified();
			    	}//不是-1行
				}
				//如果有一个为0的取大的，否则取小的
		    	if(noFiveCount==0 || fiveCount==0) {
		    		qualityCount=qualityCount+(noFiveCount>fiveCount?noFiveCount:fiveCount);
		    	}else {
		    		qualityCount=qualityCount+(noFiveCount>fiveCount?fiveCount:noFiveCount);
		    	}
			}else
			{
				//得到此工序分行号，物料，报工情况(仅原料仓)
				List<ReportBean> oneProcedureList=workShopReportList.stream().filter(pp->pp.getProcessId().equals(reportBean.getProcessId()) && orderMaterialTypeSet.contains(pp.getMachining())).collect(Collectors.toList());
			    //得到单行最小的报工数
				Integer fiveCount=0;//样式五（-1）数量
				Integer noFiveCount=0;//非样式五（-1） 数量
				Map<String, List<ReportBean>> rowGroup=oneProcedureList.stream().collect(Collectors.groupingBy(ReportBean::getRowIndex));
			    for(String rowIndex:rowGroup.keySet()) {
			    	List<ReportBean> rowList=rowGroup.get(rowIndex);
			    	Collections.sort(rowList, Comparator.comparing(ReportBean::getQualified));
			    	ReportBean reportBean2=rowList.get(0);
//			    	if("-1".equals(rowIndex)) {
//			    		//实际有用数取投料数和报工数小的
//			    		for(OrderDeatilBean de:orderDetailList) {
//			    			if(de.getRowIndex().equals(reportBean2.getRowIndex())) {
//			    				//取小值
//			    				fiveCount=(int) (reportBean2.getQualified()>de.getFeedCount()?de.getFeedCount():reportBean2.getQualified());
//			    			    break;
//			    			}
//			    		}
//			    	}else 
			    	{
			    		//实际有用数取投料数和报工数小的
			    		Integer rowRechCount=0;
			    		for(int z=0;z<orderDetailList.size();z++) {
			    			OrderDeatilBean de=orderDetailList.get(z);
			    			if(de.getRowIndex().equals(reportBean2.getRowIndex())) {
			    				//取小值
			    				rowRechCount=(int) (reportBean2.getQualified()>de.getFeedCount()?de.getFeedCount():reportBean2.getQualified());
			    			    break;
			    			}
			    		}
			    		noFiveCount=noFiveCount+rowRechCount;
			    	}//不是-1行
			    }//遍历行
			    //如果有一个为0的取大的，否则取小的
		    	if(noFiveCount==0 || fiveCount==0) {
		    		qualityCount=qualityCount+(noFiveCount>fiveCount?noFiveCount:fiveCount);
		    	}else {
		    		qualityCount=qualityCount+(noFiveCount>fiveCount?fiveCount:noFiveCount);
		    	}
			}//不是交接入库
			pbBean.setProcessName(reportBean.getProcedur());
			pbBean.setQualityCount(qualityCount);
			pbBean.setCreationTime(reportBean.getTime());
			returnList.add(pbBean);
		}
		return returnList;
	}

	/**
	 * 设置订单查询页面的参数
	 * 
	 * @param map
	 * @return
	 */
	private Map setOrderMainMapParam(Map map) {
		// 如果输入了订单信息,则忽视其他查询条件
		if (!"".equals(map.get("companyOrderId").toString()) || !"".equals(map.get("factoryId").toString())
				|| !"".equals(map.get("customer").toString()) || !"".equals(map.get("customerId").toString())) {
			map.put("startDate", null);// 忽视时间
			map.put("date", null);
		}
		return map;
	}

	
	
	/**
	 * 获取订单车间生产状况备份
	 * @param order
	 * @param company
	 * @param workShop
	 * @param listDetail
	 * @param deptId
	 * @return
	 * @throws ParseException
	 */
//	private List<WorkshopProductionCycleBean> getOrderWorkShop(OrderBean order, String company, Object workShop,
//			List<QueryOrderPageBean> listDetail, String deptId) throws ParseException {
//		// 获取订单设置的没合并的车间
//		List<WorkshopProductionCycleBean> workShopIdList = new ArrayList<WorkshopProductionCycleBean>();
//		workShopIdList = orderMapper.getOrderSetNoMegerWorkShop(order.getOrderId(), company, workShop);
//		if (workShopIdList == null || workShopIdList.size() <= 0) {
//			// 获取公司所有的没有合并的车间
//			workShopIdList = orderMapper.getCompanyNoMegerWorkShopId(order.getOrderId(), company, workShop, deptId);
//		}
//		// 查询订单有没有开始生产
//		Map map = new HashMap();
//		map.put("orderId", order.getOrderId());
//		map.put("loginCompany", company);
//		if (order.getRowIndex() != null && order.getRowIndex() != 0) {
//			map.put("rowIndex", order.getRowIndex());
//		}
//		List<ReportBean> proStrList = orderMapper.getAleradyProcedureWorkShop(map);
//		// 如果已经开始生产，则看车间是否生产，否则不做处理（默认未生茶产）
//		if (null != proStrList && proStrList.size() > 0) {
//			for (WorkshopProductionCycleBean wpcb : workShopIdList) {
//				map.put("workShopId", wpcb.getId());
//				// //如果车间已经开始生产
//				ReportBean repo = this.checkWorkShopProduction(proStrList, wpcb.getId());
//				// 已经开始生产
//				if (repo != null) {
//					if (order.getSort() <= 0) {
//						wpcb.setYuJiTime("已完成");
//					} else {
//						wpcb.setYuJiTime(TimeAndUnix.timeAddDay(repo.getTime(), (int) (double) wpcb.getProcessCycle()));
//					}
//					// 获取订单在车间入库的物料
//					List<String> workTypeList = orderMapper.getWorkShopInMaterial(map);
//					wpcb.setWorkShopMaterialDetailList(this.getWorkShopMaterialInStatus(workTypeList, listDetail));
//					wpcb.setIsFinish(2);// 设置未未完成
//					map.put("workTypeList", workTypeList);
//					// 获取最后一道工序生产情况
//					List<ProcessBean> processList = orderMapper.getProcessByWorkShopId(map);
//					wpcb.setProcessList(processList);
//					// 获取已经生产完成的物料条数
//					map.put("out", 1);
//					List<Integer> yuShuList = orderMapper.getYuShuList(map);
//					// 如果出库的物料条数大于等于应生产的物料条数
//					if (yuShuList != null && yuShuList.size() > 0 && yuShuList.size() >= workTypeList.size()) {
//						wpcb.setIsFinish(1);// 设置生产完成
//						wpcb.setFinishTime(processList.get(0).getCreationTime());
//					}
//				}
//			}
//		} else {
//			if (order.getSort() < 0) {
//				for (WorkshopProductionCycleBean wpcb : workShopIdList) {
//					wpcb.setYuJiTime("已完成");
//				}
//			} else {
//				for (WorkshopProductionCycleBean wpcb : workShopIdList) {
//					wpcb.setYuJiTime("");
//				}
//			}
//		}
//		return workShopIdList;
//	}

	/**
	 * @param wpcbList(车间集合)
	 * @param id(车间id)
	 * @return
	 */
	private String getWorkShopWorkType(List<WorkshopProductionCycleBean> wpcbList, String id) {
		String xx = "";
		for (WorkshopProductionCycleBean workshopProductionCycleBean : wpcbList) {
			if (workshopProductionCycleBean.getId().equals(id)) {
				xx = workshopProductionCycleBean.getProcessingObject();
				break;
			}
		}
		return xx;
	}

	// 校验车间是否已生产
	private ReportBean checkWorkShopProduction(List<ReportBean> proStrList, String id) {
		ReportBean returnBean = null;
		for (int i=0;i<proStrList.size();i++) {
		    ReportBean str = proStrList.get(i);
			if (str.getWorkShopName().equals(id)) {
				returnBean = str;
				break;
			}
		}
		return returnBean;
	}

	/**
	 * 获取车间订单物料采购入库详情
	 * 
	 * @param workTypeList(车间加工对象)
	 * @param listDetail(物料采购入库详情)
	 * @return
	 */
	private List<QueryOrderPageBean> getWorkShopMaterialInStatus(Set<String> workTypeList,
			List<QueryOrderPageBean> listDetail) {
		List<QueryOrderPageBean> xx = new ArrayList<QueryOrderPageBean>();
		for (String str : workTypeList) {
			for (int i=0;i<listDetail.size();i++ ) {
				QueryOrderPageBean queryOrderPageBean = listDetail.get(i);
				if (str.equals(queryOrderPageBean.getMaterialType())) {
					xx.add(queryOrderPageBean);
				}
			}
		}
		return xx;
	}

	/**
	 * 获取某订单在某车间的加工对象
	 * 
	 * @param workType
	 * @param orderId(订单编号)
	 * @param workShopId(车间id)
	 * @param company(公司)
	 * @param isAllMaterial(是否获取所有物料
	 *            报过不报工的物料)
	 * @return
	 */
	// public List<String> getOrderWorkshopMaterialType(String orderId,String
	// workShopId,String company,int isAllMaterial, String workType) {
	// List<String> returnList=new ArrayList<String>();//实际返回的加工对象
	// List<MaterialTreeBean>
	// orderTypeList=orderMapper.getOrderMeType(orderId,company,isAllMaterial);
	// //订单中的加工对象
	// //如果车间没有设置加工对象,或者包含整架,返回订单所有物料类型
	// if(workType==null || "".equals(workType) || workType.indexOf("整架") !=-1) {
	// returnList=orderTypeList.stream().map(MaterialTreeBean::getMaterialType).collect(Collectors.toList());
	// return returnList;
	// }
	// //获取车间加工对象数组
	// Set<String> materialSet=new HashSet<String>();
	// String[] workTypeList=workType.split(",");
	// //获取两种都的加工对象（车间加工对象与订单物料取交）
	// for(int i=0;i<workTypeList.length;i++) {
	// for(MaterialTreeBean materialTreeBean:orderTypeList) {
	// //如果订单物料与车间物料相等 或者有整腿并且物料属于腿 或者有整框 物料属于框
	// if((materialTreeBean.getMaterialType().equals(workTypeList[i])) ||
	// (workTypeList[i].equals("整腿") && materialTreeBean.getType()==3) ||
	// (workTypeList[i].equals("整框") && materialTreeBean.getType()==2)) {
	// materialSet.add(materialTreeBean.getMaterialType());
	// }
	// }
	// }
	// returnList=new ArrayList<String>(materialSet);
	// return returnList;
	// }

	public List<Integer> getYuShuList(Map map) {
		return orderMapper.getYuShuList(map);
	}


	/**
	 * 查询公司物料表 at 2018-03-30 by 李斌
	 * 
	 * @param map
	 * @return
	 */
	public CompanyMaterialTableBean getCompanyMaterialTable(Map map) {
		if (map.get("color") != null) {
			String color = map.get("color").toString().replace(" ", "");
			map.remove("color");
			map.put("color", color);
		}
		if (map.get("colorDescription") != null) {
			String colorDescription = map.get("colorDescription").toString().replace(" ", "");
			map.remove("colorDescription");
			map.put("colorDescription", colorDescription);
		}
		if (map.get("materialType") != null) {
			String materialType = map.get("materialType").toString().replace(" ", "");
			map.remove("materialType");
			map.put("materialType", materialType);
		}
		if (map.get("materialModel") != null) {
			String materialModel = map.get("materialModel").toString().replace(" ", "");
			map.remove("materialModel");
			map.put("materialModel", materialModel);
		}
		List<CompanyMaterialTableBean> companyMaterialTables = orderMapper.getCompanyMaterialTable(map);
		CompanyMaterialTableBean companyMaterialTableBean = new CompanyMaterialTableBean();
		if (companyMaterialTables != null && companyMaterialTables.size() > 0) {
			companyMaterialTableBean = companyMaterialTables.get(0);
		}
		return companyMaterialTableBean;
	}

	/**
	 * 获取订单明细表
	 * 
	 * @param id
	 * @return
	 */
	public OrderInfoDetailBean getOrderInfoDetailById(int id) {
		return orderMapper.getOrderInfoDetailById(id);
	}

	/**
	 * 更新订单明细表
	 * 
	 * @param orderInfoDetail
	 */
	public void updateOrderInfoDetail(OrderInfoDetailBean orderInfoDetail) {
		orderMapper.updateOrderInfoDetail(orderInfoDetail);
	}

	/**
	 * 批量添加投料主表和详情表
	 * 
	 * @param map
	 * @throws ServiceException
	 * @throws ParseException
	 */
	@SuppressWarnings({ "unchecked", "unused" })
	public String saveBatchFeedOrderDetailAndMain(Map map, HttpServletRequest request)
			throws ServiceException, ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		JSONArray feedOrderDetailJSON = JSONArray.fromObject(map.get("feedOrderDetailArray").toString());
		List<FeedOrderDetailBean> feedDetailToOrderList = (List<FeedOrderDetailBean>) JSONArray
				.toCollection(feedOrderDetailJSON, FeedOrderDetailBean.class);
		JSONArray feedOrderMainJSON = JSONArray.fromObject(map.get("feedOrderMainArray").toString());
		List<FeedOrderMainBean> feedOrderMainList = (List<FeedOrderMainBean>) JSONArray.toCollection(feedOrderMainJSON,
				FeedOrderMainBean.class);
		// 用于保存订单Id
		Set<String> orderIdSet = new HashSet<String>();
		//公司设定
		CompanyBean companyBean = companyMapper.getCompany(map);
		// 用于保存投料单Id和物料代码的Map 以投料单Id为Key,物料代码为Value
		Map<String, String> FeedOrderDetailIdToMaterialCode = new HashMap<String, String>();
		for (FeedOrderMainBean feedOrderMainBean : feedOrderMainList) {
			orderIdSet.add(feedOrderMainBean.getOrderId());
		}
		Map<String, Object> orderMap = new HashMap<String, Object>();
		String feedOrderId = null;
		// 用于保存投料单明细Id,传到查询采购单方法中
		List<String> feedDetailIds = new ArrayList<String>();
		Set<String> message = new HashSet<String>();
		Integer status = 0;
		for (String orderId : orderIdSet) {
			Map<String, Object> hashMap = new HashMap<String, Object>();
			hashMap.put("id", StringUtil.getUUID());
			hashMap.put("status", status);
			hashMap.put("loginUserId", map.get("loginUserId").toString());
			hashMap.put("createTime", sdf.format(new Date()));
			hashMap.put("orderId", orderId);
			hashMap.put("loginCompany", map.get("loginCompany").toString());
			orderMap.put("orderId", orderId);
			orderMap.put("loginCompany", map.get("loginCompany"));
			FeedOrderMainBean oldFeedOrderMain = orderMapper.getFeedOrderMainByOrderId(orderMap);
			// 判断投料单主表是否重复
			if (oldFeedOrderMain == null) {
				int row = orderMapper.insertFeedMian(hashMap);
				if (row <= 0) {
					throw new ServiceException("保存投料单主表出错");
				}
			} else {
				hashMap.put("id", oldFeedOrderMain.getId());
			}
			// 遍历投料单集合
			Map<String, Object> companyMap = new HashMap<String, Object>();
			for (FeedOrderDetailBean feedOrderDetail : feedDetailToOrderList) {
				feedOrderId = feedOrderDetail.getFeedOrderId();
				if (feedOrderId != null && feedOrderId.equals(orderId)) {
					Double feedCount = feedOrderDetail.getFeedCount() != null ? feedOrderDetail.getFeedCount() : 0.0;
					Double productionUnitFeedCount = feedOrderDetail.getProductionUnitFeedCount() != null
							? feedOrderDetail.getProductionUnitFeedCount()
							: 0.0;
					Map<String, Object> feedOrderDetailMap = new HashMap<String, Object>();
					feedOrderDetailMap.put("id", StringUtil.getUUID().toString());
					feedOrderDetailMap.put("feedOrderId", hashMap.get("id"));
					feedOrderDetailMap.put("materialCode", feedOrderDetail.getMaterialCode());
					feedOrderDetailMap.put("feedCount", feedCount);
					feedOrderDetailMap.put("isBuild", 0);
					feedOrderDetailMap.put("isReceiveFinish", 0);
					feedOrderDetailMap.put("receiveCount", 0);
					//之前
					/*****获取车间已经领走的 开始*****/
					Map calWorkShopCount = new HashMap<>();
					calWorkShopCount.put("orderId", orderId);
					calWorkShopCount.put("materialType", feedOrderDetail.getMaterialType());
					calWorkShopCount.put("rowIndex", feedOrderDetail.getLineNo());
					calWorkShopCount.put("materialCode", feedOrderDetail.getMaterialCode());
					calWorkShopCount.put("loginCompany",map.get("loginCompany"));
					//得到在车间的数量
					Double receiveCount = 0.0;
					List<OrderReceiveViewBean> calWorkShopCountList = issueNoteService.getOrderReceiveCount(calWorkShopCount);
					if(calWorkShopCountList.size()>0) {
						receiveCount = calWorkShopCountList.get(0).getReceiveCount();
					}
					feedOrderDetailMap.put("receiveCount", receiveCount);
					if(receiveCount.compareTo(feedCount)>=0) {//如果领料数大于等于投料数则领料完成
						feedOrderDetailMap.put("isReceiveFinish", 1);
					}
					if(receiveCount.compareTo(feedOrderDetail.getActualFeedCount())>=0) {//如果领料数大于等于实际投料数则领料完成
						feedOrderDetailMap.put("isReceiveFinish", 1);
					}else {
						feedOrderDetailMap.put("isReceiveFinish", 0);
					}
					/*****获取车间已经领走的 结束*****/
					feedOrderDetailMap.put("productionUnitReceiveCount", 0);
					feedOrderDetailMap.put("status", status);
					feedOrderDetailMap.put("type", 1);// 为1是生产订单投料单
					// 投料单明细
					companyMap.put("company", map.get("loginCompany"));
					companyMap.put("materialCode", feedOrderDetail.getMaterialCode());
					List<CompanyMaterialTableBean> companyMaterialTableBean = companyMaterialMapper
							.getCompanyMaterialByMap(companyMap);
					if(companyBean.getIsNeedApprovalByMaterial()==1) {
						Assert.isTrue(companyMaterialTableBean.get(0).getPurchaseApproval().equals(1), "物料名称:"+companyMaterialTableBean.get(0).getMaterialName()+" 色号:"+companyMaterialTableBean.get(0).getColor()+"还未审核,请先审核物料");
					}
					companyMap.clear();
					feedOrderDetailMap.put("materialName", feedOrderDetail.getMaterialName());
					feedOrderDetailMap.put("color", feedOrderDetail.getColor());
					if (feedOrderDetail.getModal() == null || feedOrderDetail.getModal().trim().equals("")) {
						feedOrderDetailMap.put("model", companyMaterialTableBean.get(0).getModel());
					} else {
						feedOrderDetailMap.put("model", feedOrderDetail.getModal());
					}

					feedOrderDetailMap.put("providerName", feedOrderDetail.getProviderName());
					//是商城
					if(feedOrderDetail.getAgentSource().equals(2)) {
						feedOrderDetailMap.put("agent", feedOrderDetail.getAgent());
						feedOrderDetailMap.put("agentSource", feedOrderDetail.getAgentSource());
					}
					//20200407feedOrderRemark
					feedOrderDetailMap.put("feedOrderRemark", feedOrderDetail.getFeedOrderRemark());
					//20190514
					feedOrderDetailMap.put("singleFeedCount", feedOrderDetail.getSingleFeedCount());
					feedOrderDetailMap.put("actualFeedCount", feedOrderDetail.getActualFeedCount());
					feedOrderDetailMap.put("useFactoryId", feedOrderDetail.getUseFactoryId());
					feedOrderDetailMap.put("useFactoryCount", feedOrderDetail.getUseFactoryCount());
						/*校验此时使用车间id该种物料可以使用数量*/
						if(feedOrderDetail.getUseFactoryId()!=null && !"".equals(feedOrderDetail.getUseFactoryId())) {
							Map issueNoteMap = new HashMap<>();
							issueNoteMap.put("loginCompany", map.get("loginCompany").toString());
							issueNoteMap.put("workShopId", feedOrderDetail.getUseFactoryId());
							issueNoteMap.put("materialCode", feedOrderDetail.getMaterialCode());
							List<WorkshopMaterialStockCountBean> workshopMaterialStockCountBeans = issueNoteService.getWorkShopMaterialCount(issueNoteMap);
							if(workshopMaterialStockCountBeans.get(0).getStockCount()>=feedOrderDetail.getUseFactoryCount()) {
								//可用数大于这个投料单使用车间物料数没关系
							}else {
								//抛出异常
								feedOrderDetailMap.put("useFactoryId", 0);
								feedOrderDetailMap.put("useFactoryCount", 0);
								throw new ServiceException(feedOrderDetail.getMaterialName()+"车间可使用数量不足,请重新修改");
							}
						}
					if (status == 1) {
						feedOrderDetailMap.put("approvalUser", map.get("loginUserId"));
						feedOrderDetailMap.put("approvalTime", sdf.format(new Date()));
						feedOrderDetailMap.put("approvalReason", "制单人与审核人一致,自动审核");
					} else {
						message.add(feedOrderDetail.getFeedOrderId());
					}
					if (map.get("isAllCreate").toString().trim().equals("yes")) {
						feedOrderDetailMap.put("status", 1);
						feedOrderDetailMap.put("approvalUser", map.get("loginUserId"));
						feedOrderDetailMap.put("approvalTime", sdf.format(new Date()));
						feedOrderDetailMap.put("approvalReason", "同时生成采购单自动审核");
					}
					feedOrderDetailMap.put("tax", feedOrderDetail.getTax());
					feedOrderDetailMap.put("purchasePrice", feedOrderDetail.getPurchasePrice());
					feedOrderDetailMap.put("createTime", sdf.format(new Date()));
					feedOrderDetailMap.put("createUser", map.get("loginUserId"));
					feedOrderDetailMap.put("lineNo", feedOrderDetail.getLineNo());
					feedOrderDetailMap.put("materialType", feedOrderDetail.getMaterialType());
					feedOrderDetailMap.put("materialFactory", feedOrderDetail.getMaterialFactory());
					FeedOrderDetailIdToMaterialCode.put(feedOrderDetailMap.get("id").toString(),
							feedOrderDetail.getMaterialCode());
					// 添加生产单位占用数前,再次校验一下数量够不够
					Map<String, Object> productionUnitCountMap = new HashMap<String, Object>();
					// 生产单位可领数量
					productionUnitCountMap.put("materialCode", feedOrderDetail.getMaterialCode());
					productionUnitCountMap.put("materialName", feedOrderDetail.getMaterialName());
					productionUnitCountMap.put("model", feedOrderDetail.getModel());
					productionUnitCountMap.put("color",
							feedOrderDetail.getColor() == null ? "" : feedOrderDetail.getColor());
					productionUnitCountMap.put("providerName", feedOrderDetail.getProviderName());
					productionUnitCountMap.put("inOutUnit", feedOrderDetail.getUnit());
					productionUnitCountMap.put("loginCompany", map.get("loginCompany"));
					BigDecimal receiveProductionUnitCount = productionUnitFeedService
							.getProductionUnitCount(productionUnitCountMap);
					// 用户有填生产单位占用量
					if (feedOrderDetail.getProductionUnitFeedCount().doubleValue() > 0) {
						if (receiveProductionUnitCount.doubleValue() > 0) {
							BigDecimal feedProductionCount = new BigDecimal(
									feedOrderDetail.getProductionUnitFeedCount().toString());
							if (receiveProductionUnitCount.subtract(feedProductionCount).doubleValue() >= 0) {
								feedOrderDetailMap.put("productionUnitFeedCount",
										feedOrderDetail.getProductionUnitFeedCount());
							} else {
								throw new ServiceException(
										"生产单位可用数不足,目前可用:" + receiveProductionUnitCount.doubleValue());
							}
						} else {
							throw new ServiceException("生产单位可用数为0");
						}
					}
					if (feedOrderDetail.getProductionUnitFeedCount() != null
							&& feedOrderDetail.getProductionUnitFeedCount().doubleValue() > 0) {
						// 保存生产单位占用数
						FeedUseMaterialCountBean feedUseMaterialCountBean = new FeedUseMaterialCountBean();
						feedUseMaterialCountBean.setColor(feedOrderDetail.getColor());
						feedUseMaterialCountBean.setCompany(map.get("loginCompany").toString());
						feedUseMaterialCountBean.setFeedDetailId(feedOrderDetailMap.get("id").toString());
						feedUseMaterialCountBean.setFeedUseCount(0.0);
						feedUseMaterialCountBean.setMaterialName(feedOrderDetail.getMaterialName());
						feedUseMaterialCountBean.setModel(feedOrderDetail.getModal());
						feedUseMaterialCountBean
								.setProductionUnitUseCount(feedOrderDetail.getProductionUnitFeedCount());
						feedUseMaterialCountBean.setProviderName(feedOrderDetail.getProviderName());
						int feedUseRow = feedUseMaterialCountMapper
								.insertFeedUseMaterialCount(feedUseMaterialCountBean);
						if (feedUseRow < 1) {
							throw new ServiceException("保存投料单占用表出错");
						}
					}
					if (feedOrderDetail.getFeedCount() == null || feedOrderDetail.getFeedCount().doubleValue() == 0) {
						if (feedOrderDetail.getProductionUnitFeedCount() == null
								|| feedOrderDetail.getProductionUnitFeedCount() == 0) {
							throw new ServiceException("无块料占用时,投料数不能为0");
						}else {
							feedOrderDetailMap.put("orderId", orderId);
							OrderInfoDetailBean orderInfoDetail = orderMapper.getOrderInfoDetailByOrderDetail(feedOrderDetailMap);
							Assert.notNull(orderInfoDetail, "订单明细为空");
							Assert.isTrue(feedOrderDetail.getProductionUnitFeedCount().doubleValue()==Integer.parseInt(orderInfoDetail.getFeedTotal()), "占用块料数不足订单投料数");
						}
					}
					int row = orderMapper.insertFeedOrderDetailOne(feedOrderDetailMap);
					if (row <= 0) {
						throw new ServiceException("保存投料单明细表出错");
					}

					feedDetailIds.add(feedOrderDetailMap.get("id").toString());
					feedOrderDetailMap.clear();
				}
			}
		}

		/**
		 * 查询公司物料表
		 */
		CompanyMaterialTableBean paramBean = new CompanyMaterialTableBean();
		String company = map.get("loginCompany").toString();
		if (company.isEmpty()) {
			throw new ServiceException("公司名称为空异常");
		}
		paramBean.setCompany(company);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		for (Entry<String, String> entry : FeedOrderDetailIdToMaterialCode.entrySet()) {
			paramBean.setMaterialCode(entry.getValue());
			List<CompanyMaterialTableBean> lists = companyMaterialMapper.getCompanyMaterialByBean(paramBean);
			if(lists.size()<=0||lists==null) {  
				paramMap.put("materialCode",entry.getValue());
				List<MaterialBean> materialList = basicDataMapper.getMaterialDetail(paramMap);
				if(materialList!=null&&materialList.size()>0) {
					CompanyMaterialTableBean bean = new CompanyMaterialTableBean();
					bean.setMaterialCode(materialList.get(0).getMaterialCode());
					bean.setMaterialName(materialList.get(0).getMaterialName());
					bean.setMaterialType(materialList.get(0).getMaterialType());
					bean.setColor(materialList.get(0).getColor());
					//bean.setColorDescription(materialList.get(0).getColorDescription());
					bean.setCount(0.0);
					bean.setModel(materialList.get(0).getModel());
					bean.setCompany(map.get("loginCompany").toString());
					bean.setCreater(map.get("loginUserName").toString());
					bean.setLastModifier(map.get("loginUserName").toString());
					bean.setCreationTime(sdf.format(new Date()));
					bean.setLastModifyTime(sdf.format(new Date()));
					bean.setProviderName(materialList.get(0).getProviderName());
					bean.setDefaultWarehouse(materialList.get(0).getDefaultWarehouse());
					bean.setUnit(materialList.get(0).getUnit());
					bean.setUnitPrice(materialList.get(0).getUnitPrice());
					bean.setStatus(materialList.get(0).getStatus());
					bean.setProcurementCycles(materialList.get(0).getProcurementCycles());
					bean.setIsEquals(materialList.get(0).getIsEquals());
					bean.setIsStock(materialList.get(0).getIsStock());
					basicDataMapper.insertCompanyMaterialDetailAndIsStock(bean);
					paramMap.put("companyMaterialTableBean", bean);
					basicDataService.addCompanyMaterialCountOnMaterial(paramMap);
				}  
			}
			// 二次补全订单信息
			Map<String, String> orderParam = new HashMap<String, String>();
			String mainId = orderMapper.getFeedOrderDetailById(entry.getKey());
			String orderId = orderMapper.getFeedOrderMainById(mainId);
			orderParam.put("materialCode", entry.getValue());
			orderParam.put("orderId", orderId);
			OrderInfoDetailBean copeOrder = new OrderInfoDetailBean();
			List<OrderInfoDetailBean> orderInfoDetailList = orderMapper.getOrderInfoDetailByMap(orderParam);
			for (OrderInfoDetailBean orderInfoDetail : orderInfoDetailList) {
				BeanUtils.copyProperties(orderInfoDetail, copeOrder);
				int isReadColor = orderInfoDetail.getIsReadColor();
				if(isReadColor==0) {
					Map<String, String> mateiralTypeMap = new HashMap<String, String>();
					mateiralTypeMap.put("loginCompany", map.get("loginCompany").toString());
					mateiralTypeMap.put("materialType", orderInfoDetail.getMaterialType());
					CompanyMaterialTypeBean materialTreeBean = companyMaterialTypeService
							.getCompanyMaterialTypeByMateiralType(mateiralTypeMap);
					// 1是读取物料颜色
					if (materialTreeBean != null) {
						isReadColor = materialTreeBean.getIsReadColor();
					}
				}
				orderInfoDetail.setMaterialModel(lists.get(0).getModel());
				if(isReadColor==1) {
					orderInfoDetail.setColor(lists.get(0).getColor());
					//orderInfoDetail.setColorDescription(lists.get(0).getColorDescription());
				}
				if (orderInfoDetail.getSequeueNo().trim().equals("-1")) {
					Map<String, Object> orderParamMap = new HashMap<String, Object>();
					orderParamMap.put("orderNo", orderInfoDetail.getOrderNo());
					orderParamMap.put("materialType", orderInfoDetail.getMaterialType());
					orderParamMap.put("materialFatory", orderInfoDetail.getMaterialFactory());
					List<OrderInfoDetailBean> orderInfoDetailBeans = orderMapper
							.getOrderInfoTailByOrderDetail(orderParamMap);
					if (orderInfoDetailBeans != null && orderInfoDetailBeans.size() > 0) {
						OrderInfoDetailBean orderInfoTail = orderInfoDetailBeans.get(0);
						orderInfoTail.setMaterialModel(orderInfoDetail.getMaterialModel());
						if(isReadColor==1) {
							orderInfoTail.setColor(orderInfoDetail.getColor());
							orderInfoTail.setColorDescription(orderInfoDetail.getColorDescription());
						}
						orderInfoTail.setMaterialCode(orderInfoDetail.getMaterialCode());
						// 补全行号为负一的订单明细
						orderMapper.updateOrderInfoTailById(orderInfoTail);
					}
				}
				// 补全订单明细信息
				orderMapper.updateOrderInfoDetailById(orderInfoDetail);
			}
		}
		// 判断用户是否要自动生成采购单
		if (map.get("isAllCreate") != null && map.get("isAllCreate").toString().trim().equals("yes")) {
			Map<String, Object> purchaseMap = new HashMap<String, Object>();
			purchaseMap.put("loginUserId", map.get("loginUserId"));
			purchaseMap.put("loginCompany", map.get("loginCompany"));
			purchaseMap.put("loginUserName", map.get("loginUserName"));
			purchaseMap.put("ids", feedDetailIds);
			return this.getPurchaseOrderOther(purchaseMap);
		} else {
			String msg = "";
			if (status == 0) {
				StringBuffer sb = new StringBuffer();
				sb.append("工厂型号为:");
				map.put("orderList", new ArrayList<>(message));
				List<String> factoryNoList = orderMapper.getFactoryNoByOrderId(map);
				for (String factoryId : factoryNoList) {
					sb.append(factoryId + ",");
				}
				String queryId = StringUtil.getUUID();
				List<QueryOrderBean> queryOrderBeans = new ArrayList<QueryOrderBean>();
				for (String orderId : feedDetailIds) {
					QueryOrderBean queryOrderBean = new QueryOrderBean();
					queryOrderBean.setOrderId(orderId);
					queryOrderBean.setQueryId(queryId);
					queryOrderBean.setCompany(map.get("loginCompany").toString());
					queryOrderBean.setCreateTime(sdf.format(new Date()));
					queryOrderBeans.add(queryOrderBean);
				}
				map.put("queryOrderList", queryOrderBeans);
				queryOrderService.addQueryOrder(map);
				String queryCondition = "#type=1&detailId=" + queryId;
				msg = companyMaterialService.sendWechatMessage("投料单待审核通知", 3, sb.toString(), sdf.format(new Date()),
						map, RedirectUrlUtil.feddingBill + queryCondition, 0);
			}
			return msg;
		}
	}

	// 向前改订单排序
	public void updateOrderSortBrfore(Map map) {
		orderMapper.updateOrderSortBrfore(map);
	}

	// 向后改订单排序
	public void updateOrderSortAfter(Map map) {
		orderMapper.updateOrderSortAfter(map);
	}
	
	//订单设置完成
	public void updateOrderSortByFinish(Map map) {
		orderMapper.updateOrderSortByFinish(map);
	}
	

	/**
	 * 获取出入库的物料类型通过公司物料表 at 2018-04-02 by 李斌
	 * 
	 * @param map
	 * @return
	 */
	public List<String> getMaterialTypeOnWarehouseInOutDetail(Map map) {
		return orderMapper.getMaterialTypeOnWarehouseInOutDetail(map);
	}

	/**
	 * 获取订单明细
	 * @param detailList 订单明细
	 * @param notNeedPurchaseMaterialSet 不需要采购的物料类型
	 * @return
	 */
	public List<QueryOrderPageBean> getOrderInfoDetailOne(List<QueryOrderPageBean> detailList, Set<String> notNeedPurchaseMaterialSet) {
		for (int i=0;i< detailList.size();i++ ) {
			QueryOrderPageBean queryOrder = detailList.get(i);
			// 订单已设置完成
			if (queryOrder.getOrderSort() < 0) {//订单设置完成
				queryOrder.setPurchaseStatus(ReturnStringUtil.PURCHASE_ORDER_ALERADY_FINISH);
				queryOrder.setInStatus(ReturnStringUtil.PURCHASE_ORDER_ALERADY_FINISH);
			} else if(notNeedPurchaseMaterialSet.contains(queryOrder.getMaterialType())) {//物料配置不采购
				queryOrder.setPurchaseStatus(ReturnStringUtil.PURCHASE_NO_NEED);
				queryOrder.setInStatus(ReturnStringUtil.PURCHASE_NO_NEED);
			}else if("".equals(queryOrder.getPurchaseId()) || null==queryOrder.getPurchaseId()){//未采购
				Integer inCount=orderMapper.getDetailReportCount(queryOrder);
				inCount=null==inCount?0:inCount;
				queryOrder.setReportCount(inCount);
				if(0==inCount) {//未报工
					queryOrder.setPurchaseStatus(ReturnStringUtil.PURCHASE_NO);
					queryOrder.setInStatus(ReturnStringUtil.PURCHASE_NO);
				}else if(inCount>=queryOrder.getOrderTotal()){
					queryOrder.setPurchaseStatus(ReturnStringUtil.PURCHASE_NO_BUT_REPORT_FINSH);
					queryOrder.setInStatus(ReturnStringUtil.PURCHASE_NO_BUT_REPORT_FINSH);
				}else {
					queryOrder.setPurchaseStatus(ReturnStringUtil.PURCHASE_NO_BUT_REPORT_NOT_WHOLE);
					queryOrder.setInStatus(ReturnStringUtil.PURCHASE_NO_BUT_REPORT_NOT_WHOLE);
				}
			}else if(0==queryOrder.getPurchaseCount()){//有库存不采购
				queryOrder.setPurchaseStatus(ReturnStringUtil.PURCHASE_HAVE_STOCK);
				queryOrder.setInStatus(ReturnStringUtil.PURCHASE_HAVE_STOCK);
			}else {//否则为已采购
				queryOrder.setPurchaseStatus(ReturnStringUtil.PURCHASE_ALERADY);
				if(queryOrder.getInCount()==0) {//入库数为0则未入库
					queryOrder.setInStatus(ReturnStringUtil.PURCHASE_NO);
				}else if(queryOrder.getPurchaseCount()>queryOrder.getInCount()) {//入库数小于采购数，则未全部入库
					queryOrder.setInStatus(ReturnStringUtil.PURCHASE_IN_NOT_WHOLE);
				}else {//否则为未入库
					queryOrder.setInStatus(ReturnStringUtil.PURCHASE_ALERADY);
				}
			}
		}
		return detailList;
	}
//	public List<QueryOrderPageBean> getOrderInfoDetailOne(List<QueryOrderPageBean> detailList) {
//		for (int i=0;i< detailList.size();i++ ) {
//			QueryOrderPageBean queryOrder = detailList.get(i);
//			// 订单已设置完成
//			if (queryOrder.getOrderSort() < 0) {
//				queryOrder.setPurchaseStatus(1);
//				queryOrder.setInStatus(1);
//			} else if (queryOrder.getOrderNo() == null || queryOrder.getOrderNo().equals("")) {// 没有采购单
//				// 查询此物料入库情况数量
//				queryOrder.setOrderId(queryOrder.getOrderId());
//				// Integer inCount=orderMapper.getDetailReportCount(queryOrder);
//				Double inCount = queryOrder.getInCount();
//				// 没报工 采购入库都为0
//				if (inCount == null || inCount == 0) {
//					queryOrder.setPurchaseStatus(0);
//					queryOrder.setInStatus(0);
//				} else if (inCount < queryOrder.getOrderTotal()) {// 报工数小与订单数 已采购未完全入库
//					queryOrder.setPurchaseStatus(1);
//					queryOrder.setInStatus(2);
//				} else {
//					queryOrder.setPurchaseStatus(1);
//					queryOrder.setInStatus(1);
//				}
//			} else {// 有采购单 采购状态设为已采购
//				queryOrder.setPurchaseStatus(1);
//				if (queryOrder.getPurchaseCount() == 0 || queryOrder.getInCount() >= queryOrder.getPurchaseCount()) {
//					queryOrder.setInStatus(1);
//				} else if (queryOrder.getInCount() <= 0) {
//					queryOrder.setInStatus(0);
//				} else if (queryOrder.getInCount() < queryOrder.getPurchaseCount()) {
//					queryOrder.setInStatus(2);
//				}
//			}
//		}
//		return detailList;
//	}
	
	public List<QueryOrderPageBean> getOrderInfoDetail(Map map) {
		List<QueryOrderPageBean> detailList = orderMapper.getOrderInfoDetail(map);
		Set<String> notNeedPurchaseMaterialSet=this.getCompanyNotNeePurchaseMaterialType(map);
		detailList=this.getOrderInfoDetailOne(detailList,notNeedPurchaseMaterialSet);
		return detailList;
	}

	/**
	 * 获取公司物料表设置不需要采购的物料
	 * @param map
	 * @return
	 */
	private Set<String> getCompanyNotNeePurchaseMaterialType(Map map) {
		Map treeMap=new HashMap();
		treeMap.put("loginCompany", map.get("loginCompany"));
		List<MaterialTreeBean> list=structureTreeService.getCompanyMaterialTree(treeMap);
		if(null==list) {list=new ArrayList<MaterialTreeBean>();}
		return list.stream().filter(ss->2==ss.getIsPurchase()).map(MaterialTreeBean::getMaterialType).collect(Collectors.toSet());
	}

	/**
	 * 领料单业务逻辑处理 at 2018-04-03 by 李斌
	 * @param myUser
	 * @param companyMaterial
	 * @throws ServiceException
	 */
	public void saveMaterialRequisition(Map map) throws ServiceException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		CompanyMaterialTableBean companyMaterial = null;
		// 先根据接收的数据查询物料
		List<CompanyMaterialTableBean> oldCompanyMaterialList = orderMapper.getCompanyMaterialTableOnRequisition(map);
		if (oldCompanyMaterialList != null && oldCompanyMaterialList.size() > 0) {
			// 领取数量
			Double requisitionCount = Double.valueOf(map.get("count").toString());
			// 遍历查询出来的公司物料表信息.遇到数量满足的就跳出当前循环.没有就继续遍历
			for (int i = 0; i < oldCompanyMaterialList.size(); i++) {
				companyMaterial = oldCompanyMaterialList.get(i);
				if (companyMaterial.getCount() > requisitionCount) {
					break;
				}
			}
			if (requisitionCount > companyMaterial.getCount()) {
				throw new ServiceException("当前领取数量超过库存数量,最大领取数量为:" + companyMaterial.getCount());
			}
			Map<String, Object> companyMaterialMap = new HashMap<String, Object>();
			WarehouseInOutDetailBean warehouseInOutDetail = new WarehouseInOutDetailBean();
			String ckId = dingTalkMapper.getApprovalNo("CK");
			warehouseInOutDetail.setId(ckId);
			warehouseInOutDetail.setType(2);// 1是入库,2是出库
			warehouseInOutDetail.setMaterialCode(companyMaterial.getMaterialCode());
			warehouseInOutDetail.setCount(requisitionCount);
			warehouseInOutDetail.setMaterialName(companyMaterial.getMaterialName());
			warehouseInOutDetail.setMaterialType(companyMaterial.getMaterialType());
			warehouseInOutDetail.setPurcharseOrderId("");
			warehouseInOutDetail.setCreateTime(sdf.format(new Date()));
			warehouseInOutDetail.setCreateUser(map.get("loginUserId").toString());
			warehouseInOutDetail.setStatus(0);
			warehouseInOutDetail.setCompany(map.get("loginCompany").toString());
			List<WarehouseInOutDetailBean> inOutList = new ArrayList<WarehouseInOutDetailBean>();
			inOutList.add(warehouseInOutDetail);
			// 插入出库表信息
			companyMaterialMapper.insertInOutRecode(inOutList);
			// 修改公司物料库存
			companyMaterialMap.put("loginCompany", companyMaterial.getCompany());
			List<CompanyMaterialTableBean> listCompanyMaterial = new ArrayList<CompanyMaterialTableBean>();
			companyMaterial.setCount(companyMaterial.getCount() - requisitionCount);
			listCompanyMaterial.add(companyMaterial);
			companyMaterialMap.put("listCompanyMaterial", listCompanyMaterial);
			companyMaterialMapper.updateCompanyMaterialTable(companyMaterialMap);
		} else {
			throw new ServiceException("目前仓库没有符合的物料!");
		}

	}

	/**
	 * @throws ServiceException 修改采购单 @date 2018年4月14日 下午4:57:26 @author 李斌 @return
	 * void @throws
	 */
	public void updatePurchaseOrder(Map map) throws ServiceException {
		if (map.get("type") == null) {
			throw new ServiceException("没有采购单类型!");
		}
		if (map.get("tax") == null) {
			throw new ServiceException("税率不能为空!");
		}
		if (map.get("id") == null) {
			throw new ServiceException("税率不能为空!");
		}
		String type = map.get("type").toString();
		if (type.equals("2")) {
			int row = orderMapper.updatePurchaseDetail(map);
			if (row <= 0) {
				throw new ServiceException("修改采购单明细异常");
			}
		}
	}

	// 获取查询的采购单的物料信息 通过采购单号或者物料代码查询
	public List<QueryPurchaseBean> getPurchaseMaterial(Map map) {
		return orderMapper.getPurchaseMaterial(map);
	}

	// 通过id获取投料单明细
	public FeedOrderDetailBean getFeedOrderDetailOneById(String id) {
		return orderMapper.getFeedOrderDetailOneById(id);
	}

	/**
	 * 修改采购单明细数据,通过type区分修改内容 @date 2018年5月11日 下午2:13:09 @author 李斌 @return
	 * void @throws
	 */
	public void updatePurchaseOrderDetail(Map<String, Object> map) {
		orderMapper.upatePurchaseOrderDetailOnDetailById(map);
	}

	// 校验其他部门
	public List<String> checkOtherDept(Map map) {
		return orderMapper.checkOtherDept(map);
	}

	// 获取订单外报工部门
	public List<OtherReportDeptBean> getOtherDept(Map map) {
		return orderMapper.OtherReportDeptBean(map);
	}

	// 添加其他部门
	public void addOtherDept(Map map) {
		String deptArray = map.get("deptArray").toString();
		JSONArray jsonArray = JSONArray.fromObject(deptArray);
		List<String> idList = jsonArray.subList(0, jsonArray.size());
		map.put("deptList", idList);
		orderMapper.addOtherDept(map);
	}

	/**
	 * 获取出入库的物料名称 @date 2018年5月15日 上午8:50:39 @author 李斌 @return List<String> @throws
	 */
	public List<String> getMaterialNameOnWarehouseInOutDetail(Map map) {
		return orderMapper.getMaterialNameOnWarehouseInOutDetail(map);
	}

	/**
	 * 批量修改复期和打印状态 @date 2018年5月15日 上午9:59:40 @author 李斌 @return void @throws
	 */
	public void updateBatchPurchaseOrderDetail(Map<String, Object> map) {
		Object idsObj = map.get("ids");
		if (idsObj != null) {
			String[] ids = idsObj.toString().split(",");
			map.put("ids", ids);
			if(map.get("ptId") !=null && !"".equals(map.get("ptId"))) {
				//新增采购号和采购id对应数据
				purchaseOrderService.addPurchasePrint(map);
			}
		}
		orderMapper.updateBatchPurchaseOrderDetail(map);
	}

	/**
	 * 获取采购单的所有供应商 @date 2018年5月16日 上午8:51:18 @author 李斌 @return Object @throws
	 */
	public List<String> getProviderNameByPurchaseOrder(Map<String, Object> map) {
		return orderMapper.getProviderNameByPurchaseOrder(map);
	}

	/**
	 * @throws ServiceException 批量审核采购单 @date 2018年5月17日 上午8:26:59 @author
	 * 李斌 @return void @throws
	 */
	public String setAllPurchaseStatus(Map<String, Object> map) throws ServiceException {
		Map<String, Object> approvalParam = new HashMap<String, Object>();
		approvalParam.put("type", "4");
		approvalParam.put("loginUserId", map.get("loginUserId"));
		approvalParam.put("loginCompany", map.get("loginCompany"));
		List<String> userIds = approvalService.getApprovalIdByLoginId(approvalParam);
		String[] idList = null;
		idList = map.get("ids").toString().split(",");
		map.put("idList", idList);
		List<String> users = orderMapper.getPurchaseCreateIdByIds(map);
		String isStatus = "0";
		if (userIds != null && userIds.size() > 0) {
			out: for (String id : userIds) {
				for (String createId : users) {
					if (id.equals(createId)) {
						isStatus = "1";
						break out;
					}
				}
			}
			if (isStatus.equals("0")) {
				throw new ServiceException("您暂无权限审核此采购单!");
			}
		} else {
			if (isStatus.equals("0")) {
				throw new ServiceException("您暂无权限审核此采购单!");
			}
		}
		if (map.get("type") != null && map.get("ids") != null) {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
			map.put("approvalTime", simpleDateFormat.format(new Date()));
			String type = map.get("type").toString();
			String[] ids = null;
			if (type.trim().equals("1")) {// 订单采购单
				ids = map.get("ids").toString().split(",");
				map.put("ids", ids);
				orderMapper.setAllPurchaseStatus(map);
			} else if (type.trim().equals("2")) {// 库存采购单
				ids = map.get("ids").toString().split(",");
				map.put("ids", ids);
				orderMapper.setAllPurchaseStatus(map);
			} else {
				throw new ServiceException("无此类型的采购单");
			}
		} else {
			throw new ServiceException("参数不齐异常");
		}

		approvalParam.put("users", users);
		List<UserBean> userBeans = userService.getUserByIds(approvalParam);
		StringBuffer sb = new StringBuffer();
		for (UserBean userBean : userBeans) {
			String message = workshopService.sendApprovalStatusMassage(1, userBean.getId(),
					map.get("loginUserName").toString(), "采购单审批通知", RedirectUrlUtil.queryPurchaseOrder);
			if (!message.isEmpty()) {
				sb.append(userBean.getUserName() + " 因未关联微信公众,未收到微信信息,请口头告知");
			}
		}
		return sb.toString();
	}

	/**
	 * 设置订单车间生产顺序
	 * 
	 * @param orderId
	 * @param workShopId
	 * @param time
	 * @return
	 * @throws ServiceException
	 */
	public void setOrderWorkShopTime(Map map) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		map.put("createTime", simpleDateFormat.format(new Date()));
		map.put("id", StringUtil.getUUID());
		orderMapper.deletetOrderWorkShopTime(map);
		orderMapper.insertOrderWorkShopTime(map);
	}

	/**
	 * 修改订单下单日期
	 * 
	 * @param orderId
	 * @param time
	 * @return
	 * @throws ServiceException
	 */
	public void updateOrderXianDanDate(Map map) {
		orderMapper.updateOrderXianDanDate(map);
	}

	/**
	 * 修改投料单物料信息 @date 2018年6月11日 下午7:53:12 @author 李斌 @return void @throws
	 */
	public int updateFeedDetailMaterial(Map<String, Object> map) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// 获取投料单明细信息
		FeedOrderDetailBean feedOrderDetailBean = orderMapper.getFeedOrderDetailOneById(map.get("detailId").toString());
		if (feedOrderDetailBean == null) {
			throw new ServiceException("无投料单明细异常");
		} 
		map.put("feedOrderId", feedOrderDetailBean.getFeedOrderId());
		// 获取订单编号
		String orderId = orderMapper.getOrderIdOnFeedOrderMain(map);
		if (orderId == null) {
			throw new ServiceException("无订单编号异常");
		}
		if (map.get("feedCount") != null) {
			if (Double.valueOf(map.get("feedCount").toString()) <= 0) {
				throw new ServiceException("投料数不能修改为0");
			}
		}
		map.put("feedDetailId", feedOrderDetailBean.getId());
		if (feedOrderDetailBean.getIsBuild() == 1) {
			throw new ServiceException("该投料单已生成采购单无法修改");
		} else {
			// 获取生产订单明细
			map.put("orderId", orderId);
			map.put("lineNo", feedOrderDetailBean.getLineNo());
			map.put("materialType", feedOrderDetailBean.getMaterialType());
			map.put("materialFactory", feedOrderDetailBean.getMaterialFactory());
			OrderInfoDetailBean orderInfoDetailBean = orderMapper.getOrderInfoDetailByOrderDetail(map);
			OrderInfoDetailBean copeOrder = new OrderInfoDetailBean();
			BeanUtils.copyProperties(orderInfoDetailBean, copeOrder);
			int isReadColor = 1;
			isReadColor = orderInfoDetailBean.getIsReadColor();
			if (orderInfoDetailBean == null) {
				throw new ServiceException("无订单明细信息异常");
			}
			map.remove("materialType");
			if (map.get("color") == null) {
				map.put("color", "");
			}
			List<CompanyMaterialTableBean> companyMaterialTableBeans = basicDataMapper
					.getUniqueCompanyMaterialByDetail(map);
			CompanyMaterialTableBean companyMaterialTableBean = null;
			if (companyMaterialTableBeans != null && companyMaterialTableBeans.size() > 0) {
				for (int i = 0; i < companyMaterialTableBeans.size(); i++) {
					if (companyMaterialTableBeans.get(i).getMaterialCode() != null
							&& !companyMaterialTableBeans.get(i).getMaterialCode().equals("")) {
						companyMaterialTableBean = companyMaterialTableBeans.get(i);
						break;
					}
				}
				if (companyMaterialTableBean != null) {
					// 更新订单
					orderInfoDetailBean.setMaterialCode(companyMaterialTableBean.getMaterialCode());
					orderInfoDetailBean.setMaterialName(companyMaterialTableBean.getMaterialName());
					if(isReadColor==1) {
						orderInfoDetailBean.setColor(companyMaterialTableBean.getColor());
						orderInfoDetailBean.setColorDescription(companyMaterialTableBean.getColorDescription());
					}
					orderInfoDetailBean.setMaterialModel(companyMaterialTableBean.getModel());
					orderMapper.updateOrderInfoDetailById(orderInfoDetailBean);
					// 更新投料单
					feedOrderDetailBean.setMaterialCode(companyMaterialTableBean.getMaterialCode());
					feedOrderDetailBean.setMaterialName(companyMaterialTableBean.getMaterialName());
					feedOrderDetailBean.setModel(companyMaterialTableBean.getModel());
					feedOrderDetailBean.setProviderName(companyMaterialTableBean.getProviderName());
					feedOrderDetailBean.setColor(companyMaterialTableBean.getColor());
					if (map.get("feedCount") != null && !map.get("feedCount").toString().trim().equals("")) {
						feedOrderDetailBean.setFeedCount(Double.valueOf(map.get("feedCount").toString()));
					}
					orderMapper.updateFeedDetailByMaterial(feedOrderDetailBean);
				}
			} else {
				companyMaterialTableBean = new CompanyMaterialTableBean();
				companyMaterialTableBean.setMaterialName(map.get("materialName").toString());
				companyMaterialTableBean.setMaterialType(feedOrderDetailBean.getMaterialType());
				companyMaterialTableBean.setModel(map.get("model").toString());
				if(isReadColor==1) {
					companyMaterialTableBean.setColor(map.get("color")==null?"":map.get("color").toString());
					companyMaterialTableBean.setColorDescription(map.get("colorDescription")==null ? "" :map.get("colorDescription").toString());
				} else {
					companyMaterialTableBean.setColor("");
					companyMaterialTableBean.setColorDescription("");
				}
				companyMaterialTableBean.setProviderName(map.get("providerName").toString());
				companyMaterialTableBean.setMaterialCode(basicDataService.setCompanyMaterialCode(
						companyMaterialTableBean.getProviderName(), companyMaterialTableBean.getMaterialName()));
				companyMaterialTableBean.setCompany(map.get("loginCompany").toString());
				companyMaterialTableBean.setCount(0.0);
				companyMaterialTableBean.setProductionUnitCount(0.0);
				companyMaterialTableBean.setStatus("使用");
				companyMaterialTableBean.setCreater(map.get("loginUserId").toString());
				companyMaterialTableBean.setCreationTime(simpleDateFormat.format(new Date()));
				companyMaterialTableBean
						.setIsEquals(map.get("isEquals") == null ? 1 : Integer.valueOf(map.get("isEquals").toString()));
				if (map.get("unit") == null) {
					throw new ServiceException("无物料单位异常");
				}
				companyMaterialTableBean.setUnit(map.get("unit").toString());
				companyMaterialTableBean.setUnitPrice(
						map.get("unitPrice") == null ? 0.0f : Double.valueOf(map.get("unitPrice").toString()));
				companyMaterialTableBean.setDefaultWarehouse(
						map.get("defaultWarehouse") == null ? "原材料仓" : map.get("defaultWarehouse").toString());
				companyMaterialTableBean.setProcurementCycles(map.get("procurementCycles") == null ? 0
						: Integer.valueOf(map.get("procurementCycles").toString()));
				companyMaterialTableBean.setMaterial(map.get("material") == null ? "" : map.get("material").toString());
				companyMaterialTableBean.setTransmittance(
						map.get("transmittance") == null ? 0.0 : Double.valueOf(map.get("transmittance").toString()));
				basicDataMapper.insertCompanyMaterialDetail(companyMaterialTableBean);
				// 更新投料单
				feedOrderDetailBean.setMaterialCode(companyMaterialTableBean.getMaterialCode());
				feedOrderDetailBean.setMaterialName(companyMaterialTableBean.getMaterialName());
				feedOrderDetailBean.setModel(companyMaterialTableBean.getModel());
				feedOrderDetailBean.setProviderName(companyMaterialTableBean.getProviderName());
				feedOrderDetailBean.setColor(companyMaterialTableBean.getColor());
				if (map.get("feedCount") != null && !map.get("feedCount").toString().trim().equals("")) {
					feedOrderDetailBean.setFeedCount(Double.valueOf(map.get("feedCount").toString()));
				}
				orderMapper.updateFeedDetailByMaterial(feedOrderDetailBean);
				// 更新订单
				orderInfoDetailBean.setMaterialCode(companyMaterialTableBean.getMaterialCode());
				orderInfoDetailBean.setMaterialName(companyMaterialTableBean.getMaterialName());
				if(isReadColor == 1) {
					orderInfoDetailBean.setColor(companyMaterialTableBean.getColor());
					orderInfoDetailBean.setColorDescription(companyMaterialTableBean.getColorDescription());
				}
				orderInfoDetailBean.setMaterialModel(companyMaterialTableBean.getModel());
				orderMapper.updateOrderInfoDetailById(orderInfoDetailBean);
			}
			// 如果之前有用到生产单位库存
			if (feedOrderDetailBean.getProductionUnitFeedCount().doubleValue() > 0) {
				map.put("feedDetailId", feedOrderDetailBean.getId());
				List<FeedUseMaterialCountBean> feedUseMaterialCountBeans = feedUseMaterialCountMapper
						.getFeedUseMaterialCountByFeedDetailId(map);
				if (feedUseMaterialCountBeans != null && feedUseMaterialCountBeans.size() > 0) {
					int row = feedUseMaterialCountMapper.deleteFeedUseMaterialById(feedUseMaterialCountBeans.get(0));
					Assert.isTrue(row > 0, "消除生产单位占用信息异常");
					feedOrderDetailBean.setProductionUnitFeedCount(null);
					int feedRow = orderMapper.updateProductionFeedCount(feedOrderDetailBean);
					Assert.isTrue(row > 0, "消除投料单生产单位占用信息异常");
					return 1;
				} else {
					throw new ServiceException("无生产单位占用信息异常");
				}
			}
			return 0;
		}
	}

	/**
	 * 出库其他仓位的物料 @date 2018年6月19日 下午5:21:54 @author 李斌 @return
	 * List<FeedOrderDetailBean> @throws
	 */
	public DatatablesViewPageBean<FeedOrderDetailBean> getOtherWarehouseData(Map map) {
		int start = 0;
		int length = 0;
		List<FeedOrderDetailBean> feedOrderDetailBeans = otherWarehouseMapper.getOtherWarehouseByWarehouseOut(map);
		// 返回的数据
		List<FeedOrderDetailBean> resultData = new ArrayList<FeedOrderDetailBean>();
		DatatablesViewPageBean<FeedOrderDetailBean> datatablesViewPageBean = new DatatablesViewPageBean<FeedOrderDetailBean>();
		if (map.get("start") != null) {
			start = Integer.parseInt(map.get("start").toString());
			map.remove("start");
		}
		if (map.get("length") != null) {
			length = Integer.parseInt(map.get("length").toString());
			map.remove("length");
		}
		String deptId = null;
		if (map.get("loginUserDeptId") != null) {
			deptId = map.get("loginUserDeptId").toString();
		} else {
			throw new ServiceException("登录人员无部门,无法获取仓库物料信息");
		}
		if (feedOrderDetailBeans == null || feedOrderDetailBeans.size() < 1) {
			throw new ServiceException("无物料信息");
		}
		for (FeedOrderDetailBean feedOrderDetailBean : feedOrderDetailBeans) {
			if (feedOrderDetailBean.getOrderId() != null && !feedOrderDetailBean.getOrderId().trim().equals("")) {
				if (deptId.equals(feedOrderDetailBean.getDeptId())) {
					resultData.add(feedOrderDetailBean);
				}
			} else {
				resultData.add(feedOrderDetailBean);
			}
		}
		if (resultData.size() < 1) {
			throw new ServiceException("无法获取其他部门的物料信息");
		}
		int count = resultData.size();
		int leng = start + length;
		if (leng > count) {
			leng = count;
		}
		resultData = resultData.subList(start, leng);
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		datatablesViewPageBean.setiTotalRecords(count);
		datatablesViewPageBean.setReturnData(resultData);
		return datatablesViewPageBean;
	}

	/**
	 * 校验采购单是否可被退回 @date 2018年7月26日 上午9:38:28 @author 李斌 @return boolean @throws
	 */
	public int isRetreatPurchaseOrder(Map<String, Object> map) {

		// 返回int
		/**
		 * 返回1 说明 需退回投料单 返回2 无需退回投料单 返回3 无需退回投料单,但是提示仓库库存不足投料单
		 */
		// 获取采购单投料单对应表数据
		PurchaseOrderDetailBean purchaseOrderDetailBean = (PurchaseOrderDetailBean) map.get("purchaseOrderDetail");
		if (purchaseOrderDetailBean == null) {
			throw new ServiceException("采购单明细为空异常");
		}
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("loginCompany", map.get("loginCompany"));
		// 获取修改记录applyId
		paramMap.put("orderId", purchaseOrderDetailBean.getOrderId());
		String applyId = orderMapper.getApplyIdByOrderId(paramMap);
		// 获取订单修改记录信息与原纪录
		paramMap.put("applyId", applyId);
		paramMap.put("lineNo", purchaseOrderDetailBean.getLineNo());
		paramMap.put("materialFactory", purchaseOrderDetailBean.getMaterialFactory());
		paramMap.put("materialType", purchaseOrderDetailBean.getMaterialType());
		List<OrderInfoDetailSourceAndApplyBean> orderList = orderMapper.getOrderInfoDetailSourceAndApply(paramMap);
		if (orderList == null || orderList.size() < 1) {
			throw new ServiceException("无订单修改记录异常");
		}
		for (OrderInfoDetailSourceAndApplyBean order : orderList) {
			// 原订单投料数
			BigDecimal feedTotal = new BigDecimal(order.getFeedTotal());
			// 修改后的订单投料数
			BigDecimal applyFeedTotal = new BigDecimal(order.getApplyFeedTotal());
			ReportBean reportBean = new ReportBean();
			reportBean.setOrderId(order.getOrderNo());// 订单编号
			reportBean.setMachining(order.getMaterialType());// 物料类型
			reportBean.setRowIndex(order.getLineNo());// 行号
			// 得到在车间的数量
			long count = workshopService.getOrderAllWorkShopTurnoverCount(reportBean);
			// 判断车间物料是否全部退回
			if (applyFeedTotal.longValue() < count) {
				/*String msg = "请先检查订单号[" + order.getOrderNo() + "]序号[" + order.getLineNo() + "]物料["
						+ order.getMaterialType() + "]还需退回仓库[" + (count - Float.valueOf(order.getApplyFeedTotal()))
						+ "付]\r\n";*/
				//throw new ServiceException(msg);
			}
			// 判断物料是否修改过
			if (!order.getMaterialCode().equals(order.getApplyMaterialCode())) {
				return 1;
			}
			// 如果订单投料数改小
			if (feedTotal.subtract(applyFeedTotal).doubleValue() > 0) {
				// 调用校验方法
				// paramMap.put("feedDetailId",purchaseOrderDetailBean.getFeedDetailId());
				// paramMap.put("oldFeedTotal", feedTotal);
				// paramMap.put("newFeedTotal", applyFeedTotal);
				// paramMap.put("materialCode", order.getMaterialCode());
				// //退回到仓库的物料(付)
				// Double returnToWarehouseCount =
				// warehouseService.returnToMaterialByFeed(paramMap);
				// //如果退回到仓库的数量大于等于原订单投料数-申请修改的订单投料数 那么就退回投料单
				// if(returnToWarehouseCount.doubleValue()>=(feedTotal.subtract(applyFeedTotal).doubleValue()))
				// {
				// return 1;
				// }else {
				// String msg
				// ="请先检查订单号["+order.getOrderNo()+"]序号["+order.getLineNo()+"]物料["+order.getMaterialType()+"]还需退回仓库["+(feedTotal.subtract(applyFeedTotal).doubleValue()-returnToWarehouseCount.doubleValue())+"付]\r\n";
				// throw new ServiceException(msg);
				// }
				return 2;
			} else if (feedTotal.subtract(applyFeedTotal).doubleValue() < 0) {
				return 1;
			} else if (feedTotal.subtract(applyFeedTotal).doubleValue() == 0) {
				return 2;
			}
		}
		return -1;
	}

	/**
	 * 获取订单审核图片
	 * @param request
	 * @param orderId(订单编号)
	 * @return
	 * @throws ServiceException
	 */
	public String getOrderApprovalImg(Map<String, Object> map) {
		return orderMapper.getOrderApprovalImg(map);
	}

	/**
	 * 通过投料单明细ids获取投料单信息 @date 2018年8月4日 上午8:00:18 @author 李斌 @return
	 * List<FeedOrderDetailPojo> @throws
	 */
	public List<FeedOrderDetailPojo> getFeedOrderDetailByDetailIds(Map<String, Object> map) {
		String queryId = null;
		if (map.get("detailId") == null) {
			throw new ServiceException("参数传递错误,detailId为空");
		}
		queryId = map.get("detailId").toString().trim();
		map.put("queryId", queryId);
		// 获取对应queryId的所有orderId
		List<String> orderIds = queryOrderService.getOrderIdsByQueryId(map);
		map.put("detailId", orderIds);
		List<FeedOrderDetailPojo> feedOrderDetailPojos = orderMapper.getFeedOrderData(map);
		return feedOrderDetailPojos;
	}
	
	/**
	 * 通过订单明细信息获取投料信息
	 */
	public List<FeedOrderDetailBean> getFeedOrderDetailByDetail (Map map){
		return  orderMapper.getFeedOrderDetailByDetail(map);
	}
	

	/**
	 * 获取订单物料报工情况
	 * @param orderId(订单编号)
	 * @return
	 * @throws ServiceException
	 */
	public List<ReportBean> getOrderMaterialReport(Map map) {
		return orderMapper.getOrderMaterialReport(map);
	}

	/**
	 * 订单查询页面导出excle
	 * 
	 * @param resultMap
	 * @param tempFolder
	 * @param tableHeadFields
	 * @param changeHead
	 * @param fields
	 * @return
	 */
	public File createExcelFile(Map resultMap, String tempFolder, String[] tableHeadFields, String[] changeHead,
			String[] fields) throws IllegalAccessException {
		List<WorkshopProductionCycleBean> workShopList = (List<WorkshopProductionCycleBean>) resultMap
				.get("deptWorkShop");
		File outFile = new File(tempFolder, UUID.randomUUID().toString() + ".xlsx");
		if (!outFile.getParentFile().exists()) {
			outFile.getParentFile().mkdirs();
		}
		Workbook wb;
		OutputStream fos = null;

		try {
			wb = new XSSFWorkbook();
			Sheet sheet = wb.createSheet();
			int rowIndex = 0;
			int colIndex = 0;
			Row row;
			Cell cell;
			row = sheet.createRow(rowIndex);
			for (String ss : tableHeadFields) {
				cell = row.createCell(colIndex);
				cell.setCellValue(ss);
				colIndex++;
			}
			for (WorkshopProductionCycleBean workShop : workShopList) {
				cell = row.createCell(colIndex);
				cell.setCellValue(workShop.getWorkshopName());
				colIndex++;
				for (int i = 0; i < changeHead.length - 1; i++) {
					cell = row.createCell(colIndex);
					cell.setCellValue("");
					colIndex++;
				}
			}
			rowIndex++;
			colIndex = 0;
			row = sheet.createRow(rowIndex);
			for (String ss : tableHeadFields) {
				cell = row.createCell(colIndex);
				cell.setCellValue("");
				colIndex++;
			}
			for (WorkshopProductionCycleBean workShop : workShopList) {
				for (String s : changeHead) {
					cell = row.createCell(colIndex);
					cell.setCellValue(s);
					colIndex++;
				}
			}
			// 合并单元格
			for (int i = 0; i < tableHeadFields.length; i++) {
				sheet.addMergedRegion(new CellRangeAddress(0, 1, i, i));
			}
			int len = tableHeadFields.length;
			for (WorkshopProductionCycleBean workShop : workShopList) {
				sheet.addMergedRegion(new CellRangeAddress(0, 0, len, len + changeHead.length - 1));
				len = len + changeHead.length;
			}
			// 订单实际数据
			DatatablesViewPageBean<OrderBean> data = (DatatablesViewPageBean<OrderBean>) resultMap.get("orderList");
			List<OrderBean> orderList = data.getReturnData();
			for (OrderBean order : orderList) {
				rowIndex++;
				colIndex = 0;
				row = sheet.createRow(rowIndex);
				for (String str : fields) {
					cell = row.createCell(colIndex);
					Field field;
					try {
						field = order.getClass().getDeclaredField(str);
						field.setAccessible(true);
						System.out.println(str);
						String value = field.get(order).toString();
						if (str.equals("purchaseStatus") || str.equals("inStatus")) {
							if (value.equals("0")) {
								cell.setCellValue("否");
							}
							if (value.equals("1")) {
								cell.setCellValue("是");
							}
							if (value.equals("2")) {
								cell.setCellValue("部分");
							}
						} else if (str.equals("putOutStatus")) {
							if (value.equals("0")) {
								cell.setCellValue("无外协");
							}
							if (value.equals("1")) {
								cell.setCellValue("完成");
							}
							if (value.equals("2")) {
								cell.setCellValue("未完成");
							}
						} else if (str.equals("companyOrderId")) {
							if (value == null || value.equals("")) {
								field = order.getClass().getDeclaredField("orderId");
								field.setAccessible(true);
								value = field.get(order).toString();
								cell.setCellValue(value);
							} else {
								cell.setCellValue(value);
							}
						} else {
							cell.setCellValue(value);
						}
					} catch (NoSuchFieldException e) {
						cell.setCellValue("");
					} catch (SecurityException e) {
						cell.setCellValue("");
					} catch (NullPointerException e) {
						cell.setCellValue("");
					}
					colIndex++;
				}

				for (WorkshopProductionCycleBean workShopTitle : workShopList) {
					boolean workShopIsHave = true;
					for (WorkshopProductionCycleBean workShop : order.getWpcbList()) {
						if (workShopTitle.getId().equals(workShop.getId())) {
							workShopIsHave = false;
							List<ProcessBean> processBeanList = workShop.getProcessList();
							ProcessBean processBean = null;
							if (processBeanList == null || processBeanList.size() <= 0) {
								processBean = new ProcessBean();
								processBean.setProcessName("");
								processBean.setQualityCount(0);
								processBean.setCreationTime("");
							} else {
								processBean = processBeanList.get(0);
							}
							cell = row.createCell(colIndex);
							if (workShop.getIsFinish() == 0) {
								cell.setCellValue("未完成");
							}
							if (workShop.getIsFinish() == 1) {
								cell.setCellValue("已完成");
							}
							if (workShop.getIsFinish() == 2) {
								cell.setCellValue(processBean.getProcessName());
							}
							colIndex++;

							cell = row.createCell(colIndex);
							cell.setCellValue(workShop.getPeopleSetTime());
							colIndex++;

							cell = row.createCell(colIndex);
							if (workShop.getWorkShopMaterialDetailList() == null
									|| workShop.getWorkShopMaterialDetailList().size() <= 0) {
								cell.setCellValue("未到齐");
							} else {
								boolean bool = true;
								for (QueryOrderPageBean qb : workShop.getWorkShopMaterialDetailList()) {
									if (qb.getInStatus() == 2) {
										bool = false;
										break;
									}
								}
								if (bool) {
									cell.setCellValue("已到齐");
								} else {
									cell.setCellValue("部分到齐");
								}
							}
							colIndex++;

							cell = row.createCell(colIndex);
							if (workShop.getIsFinish() == 1) {
								cell.setCellValue(processBean.getCreationTime());
							} else {
								cell.setCellValue("");
							}
							colIndex++;

							cell = row.createCell(colIndex);
							cell.setCellValue(workShop.getYuJiTime());
							colIndex++;

							cell = row.createCell(colIndex);
							cell.setCellValue(
									processBean.getQualityCount() == null ? 0 : processBean.getQualityCount());
							colIndex++;
							break;
						}
					}
					int magerCol = colIndex;
					if (workShopIsHave) {
						for (int i = 0; i < changeHead.length; i++) {
							cell = row.createCell(colIndex);
							if (i == 0) {
								cell.setCellValue("无需生产");
							} else {
								cell.setCellValue("");
							}
							colIndex++;
						}
						sheet.addMergedRegion(
								new CellRangeAddress(rowIndex, rowIndex, magerCol, magerCol + changeHead.length - 1));
					}
				}

			}
			// for (Object o : list) {
			// row=sheet.createRow(rowIndex);
			// List<String> line=getLineFromObject(o,fields);
			// colIndex = 0;
			// for(String sss:line){
			// cell = row.createCell(colIndex);
			// cell.setCellValue(sss);
			// colIndex++;
			// }
			//// line.forEach(rowWrite->{
			//// Cell cell = row.createCell(colIndex);
			//// cell.setCellValue(rowWrite);
			//// colIndex++;
			//// });
			// rowIndex++;
			// }

			fos = new FileOutputStream(outFile);
			wb.write(fos);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != fos)
					fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return outFile;
	}

	/**
	 * 获取要生成采购单的物料出入库记录 @date 2018年9月7日 下午4:49:44 @author 李斌 @return
	 * Map<String,Object> @throws
	 */
	public void getWarehouseInOutByMateiralOnNotStatus(Map<String, Object> map) {
		// 物料代码为空
		Map<String, Object> paramMap = new HashMap<String, Object>();
		if (map.get("materialCode") == null) {
			throw new ServiceException("物料代码为空");
		}
		paramMap.put("loginCompany", map.get("loginCompany"));
		paramMap.put("materialCode", map.get("materialCode"));	
		paramMap.put("status", "0");
		paramMap.put("isFinance",1);
		List<WarehouseInOutDetailBean> warehouseInOutDetailBeans = warehouseMapper
				.getWarehouseInOutDetailData(paramMap);
		/*if (warehouseInOutDetailBeans != null && warehouseInOutDetailBeans.size() > 0) {
			throw new ServiceException("该订单的物料有出入库记录未审核,请先审核后再生成采购单");
		}*/
	}

	/**
	 * 发送采购单价异常信息 @date 2018年9月11日 上午8:58:38 @author 李斌 @return void @throws
	 */
	public void sendUnitPriceAnomaliesMsg(String titel, String bodyMessage, String dateString, Map paramMap,
			String pageType) {
		bodyMessage = bodyMessage + "(免登录查看)";
		List<String> userIds = null;
		String orderName = null;
		// 获取异常消息推送人
		List<String> userIdList = weChatToMessageService
				.getWeChatNewsUserIdListByParam(paramMap.get("loginCompany").toString(), null, null, "10");
		orderName = "采购单";
		if (userIdList == null || userIdList.size() < 1) {
			return;
		}
		paramMap.put("userIds", userIdList);
		List<String> openIdList = weiXinPeopleService.getOpenIdByUserIds(paramMap);
		String accessToken = null;
		try {
			accessToken = weiXinService.getAccessToken(null);
		} catch (RuntimeException e) {
			return;
		}
		// 发送信息
		for (String openId : openIdList) {
			com.alibaba.fastjson.JSONObject json = WeixinTemplateList.packJsonToWarningNotice(titel, orderName,
					dateString, bodyMessage, null, null, null, null);
			String xx = WeixinTemplateSender.sendWechatmsgToUser(openId, WeiXinParamesUtil.exceptionTemplateID,
					WeiXinParamesUtil.messageLink + "?loginToken=" + openId + "&pageType=" + pageType, json,
					accessToken);
		}
	}

	/**
	 * 获取投料单被退回的已出库数量 @date 2018年9月29日 下午1:17:34 @author 李斌 @return Double @throws
	 */
	public Double getReturnFeedOrderOnOutWarehouseCount(Map<String, Object> map) {
		// 逻辑 : 用当前投料单的信息(物料代码,行号,订单编号,物料类型,仓位)
		// 找出 已出库存并且是退回的
		Assert.notNull(map.get("loginCompany"), "公司名为空");
		Assert.notNull(map.get("orderId"), "订单编号为空");
		if (map.get("lineNo") == null || map.get("materialFactory") == null || map.get("materialType") == null
				|| map.get("materialCode") == null) {
			return 0.0;
		}
		List<FeedOrderDetailBean> feedOrderDetailList = orderMapper.getFeedOrderDetailByOrderDetail(map);
		if (feedOrderDetailList == null || feedOrderDetailList.size() < 1) {
			return 0.0;
		}
		Set<String> feedDetailIdSet = new HashSet<String>();
		if (feedOrderDetailList != null && feedOrderDetailList.size() > 0) {
			for (FeedOrderDetailBean feedOrderDetailBean : feedOrderDetailList) {
				feedDetailIdSet.add(feedOrderDetailBean.getId());
			}
		}
		map.put("feedDetailIdSet", feedDetailIdSet);
		List<WarehouseInOutDetailBean> warehouseInOutDetailList = orderMapper
				.getReturnFeedOrderOnOutWarehouseCount(map);
		if (warehouseInOutDetailList == null || warehouseInOutDetailList.size() < 1) {
			return 0.0;
		}
		// 物料单位出库数
		BigDecimal outCount = new BigDecimal("0.0");
		// 生产单位出库数
		BigDecimal outProductionCount = new BigDecimal("0.0");
		for (WarehouseInOutDetailBean warehouseInOutDetailBean : warehouseInOutDetailList) {
			if (warehouseInOutDetailBean.getStatus() == 1) {
				if (warehouseInOutDetailBean.getInOutUnit() == null) {
					outCount = outCount.add(new BigDecimal(warehouseInOutDetailBean.getCount().toString()));
				} else if (warehouseInOutDetailBean.getInOutUnit().equals(warehouseInOutDetailBean.getInCountUnit())) {
					outCount = outCount.add(new BigDecimal(warehouseInOutDetailBean.getCount().toString()));
				} else {
					outProductionCount = outProductionCount
							.add(new BigDecimal(warehouseInOutDetailBean.getCount().toString()));
				}
			}
		}
		return outCount.doubleValue();
	}

	/**
	 * 获取退回的投料单的出库id @date 2018年9月30日 上午8:47:13 @author 李斌 @return
	 * List<String> @throws
	 */
	public List<String> getReturnFeedOrderOnWarehouseId(Map<String, Object> map) {
		// 逻辑 : 用当前投料单的信息(物料代码,行号,订单编号,物料类型,仓位)
		// 找出 已出库存并且是退回的
		Assert.notNull(map.get("loginCompany"), "公司名为空");
		Assert.notNull(map.get("orderId"), "订单编号为空");
		Assert.notNull(map.get("lineNo"), "行号为空");
		Assert.notNull(map.get("materialType"), "物料类型为空");
		Assert.notNull(map.get("materialFactory"), "仓位为空");
		Assert.notNull(map.get("materialCode"), "物料代码为空");
		List<String> warehouseIdList = new ArrayList<String>();
		List<FeedOrderDetailBean> feedOrderDetailList = orderMapper.getFeedOrderDetailByOrderDetail(map);
		if (feedOrderDetailList == null || feedOrderDetailList.size() < 1) {
			return null;
		}
		Set<String> feedDetailIdSet = new HashSet<String>();
		if (feedOrderDetailList != null && feedOrderDetailList.size() > 0) {
			for (FeedOrderDetailBean feedOrderDetailBean : feedOrderDetailList) {
				feedDetailIdSet.add(feedOrderDetailBean.getId());
			}
		}
		map.put("feedDetailIdSet", feedDetailIdSet);
		List<WarehouseInOutDetailBean> warehouseInOutDetailList = orderMapper
				.getReturnFeedOrderOnOutWarehouseCount(map);
		if (warehouseInOutDetailList == null || warehouseInOutDetailList.size() < 1) {
			return null;
		}
		// 物料单位出库数
		BigDecimal outCount = new BigDecimal("0.0");
		// 生产单位出库数
		BigDecimal outProductionCount = new BigDecimal("0.0");
		for (WarehouseInOutDetailBean warehouseInOutDetailBean : warehouseInOutDetailList) {
			if (warehouseInOutDetailBean.getStatus() == 1) {
				warehouseIdList.add(warehouseInOutDetailBean.getId());
			}
		}
		return warehouseIdList;
	}

	/**
	 * 检验要被退回的投料单是否有未审核出库的 @date 2018年9月30日 上午9:25:40 @author 李斌 @return
	 * void @throws
	 */
	public void isCheckReturnFeedOrderHaveWarehouseOut(Map<String, Object> map) {
		String feedDetailId = (String) map.get("feedDetailId");
		Assert.notNull(feedDetailId, "投料单id为空");
		Assert.notNull(map.get("loginCompany"), "公司名为空");
		List<WarehouseInOutDetailBean> warehouseInOutDetailList = orderMapper
				.getWarehouseOutNoApprovalByFeedDetailId(map);
		Assert.isTrue(warehouseInOutDetailList == null || warehouseInOutDetailList.size() < 1, "该投料单有出库未审核记录");
	}

	
	
	
	
	/**
	 *  查询订单物料配套
	 * @param timeType(查询的时间类型,1制单时间2交货日期)
	 * @param startDate(开始时间)
	 * @param date (结束时间)
	 * @param deptId(部门id)
	 * @param workShop(车间id)
	 * @param type(2 未完成 1 已完成)
	 * @param dutyStatus (拖期状态 1 拖期 2 即将拖期 )
	 * @param customerId(客户型号)
	 * @param customer (客户)
	 * @param companyOrderId (公司订单编号)
	 * @param factoryId(工厂型号)
	 * @param start(分页参数)
	 * @param length (分页参数)
	 * @param request
	 * @return
	 * @throws ParseException
	 * @throws CloneNotSupportedException 
	 */
	public Map getOrderMixMaterial(Map map) throws ParseException, CloneNotSupportedException {
		Map returnMap = new HashMap<>();
		int count = 0;
		// 忽略时间
		map = this.setOrderMainMapParam(map);
		map.put("queryOrderPageDateil", 1);
		DatatablesViewPageBean<OrderBean> dtcpb = new DatatablesViewPageBean<OrderBean>();
		/**
		 * 获取整报物料
		 */
		List<MaterialTreeBean> materialTreeBeans = structureTreeService.getCompanyMaterialTree(map);
		// 属于整框的物料
		List<String> kuangList = materialTreeBeans.stream().filter(material -> material.getType() == 2)
				.collect(Collectors.toList()).stream().map(MaterialTreeBean::getMaterialType)
				.collect(Collectors.toList());
		// 属于整腿的物料
		List<String> tuiList = materialTreeBeans.stream().filter(material -> material.getType() == 3)
				.collect(Collectors.toList()).stream().map(MaterialTreeBean::getMaterialType)
				.collect(Collectors.toList());
		/**
		 * 返回主信息
		 */
		// 获取查询的订单基本信息
		// 获取此条件下的订单那总条数
		OrderCountBean orderCount = orderMapper.queryOrderPageDateilCount(map);
		count=orderCount.getCount()==null?0:orderCount.getCount();
		returnMap.put("sumOrderCount", orderCount.getSumOrderCount());
		List<OrderBean> orderList = orderMapper.queryOrderPageDateil(map);
		List<PurchaseOrderBean> ordrMaterialPurchaseList = new ArrayList<PurchaseOrderBean>() ;
		List<OrderMaterial> styleFive = new ArrayList<OrderMaterial>();
		List<ReportBean> reportList= new ArrayList<ReportBean>();
		if(orderList.size()>1000) {
			int size= orderList.size();
		   	int  length=(int) Math.ceil(size/1000.0);
		   	for(int i=0;i<length;i++ ) {
		   		List<OrderBean> subList= null;
		   		if(i==length-1) {
		   			subList = orderList.subList(i*1000, size);
		   		}else {
		   			subList = orderList.subList(i*1000, (i+1)*1000);
		   		}
		   		//获取订单采购详情
		   		List<PurchaseOrderBean> tt =orderMapper.getOrdrMaterialPurchase(subList);
		   		ordrMaterialPurchaseList.addAll(tt);
		   		List<OrderMaterial> yy  =orderMapper.getOrderStyleFiveMaterial(subList);
		   		styleFive.addAll(yy);
		   		/**
		   		 * 订单物料报工情况
		   		 */
		   		List<ReportBean> ii =orderMapper.getOrderReportDeatilUserMixByOrderList(subList);
		   		reportList.addAll(ii);
		   	}
		}else {
			//获取订单采购详情
			ordrMaterialPurchaseList =orderMapper.getOrdrMaterialPurchase(orderList);
			/**
			 *  订单样式五的物料
			 */
			
			styleFive =orderMapper.getOrderStyleFiveMaterial(orderList);
			/**
			 * 订单物料报工情况
			 */
			reportList=orderMapper.getOrderReportDeatilUserMixByOrderList(orderList);
		}
		/*
		 * 获取公司配置
		 */
		CompanyBean companyBean=compangMapper.getCompany(map);
		
        //部门对应的车间物料map
		Map<String, List<WorkshopProductionCycleBean>> deptWorkShopMap=new HashMap<String,List<WorkshopProductionCycleBean>>();
		//部门车间集合
		List<WorkshopProductionCycleBean> deptWorkShopList=null;
		String paramDeptId=map.get("deptId").toString();
		
 		for(OrderBean orderBean:orderList) {
 			Set<String> aleradyCompareMaterial=new HashSet<>();
 		    if(!"".equals(paramDeptId)) {
 		    	orderBean.setDeptId(paramDeptId);
 		    }
 			//已经获取过部门下的车间
			if(deptWorkShopMap.containsKey(orderBean.getDeptId())) {
				deptWorkShopList=deptWorkShopMap.get(orderBean.getDeptId());
			}else {
				map.put("deptId", orderBean.getDeptId());
				deptWorkShopList=basicDataMapper.getDeptNoMegerWorkShop(map);
				Collections.sort(deptWorkShopList, Comparator.comparing(WorkshopProductionCycleBean::getSort).reversed());
				deptWorkShopMap.put(orderBean.getDeptId(), deptWorkShopList);
			}
			 // 订单中所有要配料的物料
			List<OrderMaterial> orderMaterials=orderBean.getOrderMaterialList();
			//加上样式五(行号为-1)的物料
			orderMaterials.addAll(styleFive.stream().filter(five-> five.getOrderId().equals(orderBean.getOrderId())).collect(Collectors.toList()));
			// 查询本订单行是否报工
			List<ReportBean> orderRowReportList=reportList.stream().filter(report->report.getOrderId().equals(orderBean.getOrderId()) && (report.getRowIndex().equals(orderBean.getRowIndex().toString()) || "-1".equals(report.getRowIndex())) && !"款".equals(report.getMachining())).collect(Collectors.toList());
			//降序排序
			//订单车间结果汇总
			List<WorkshopProductionCycleBean> orderWorkShop=new ArrayList<WorkshopProductionCycleBean>();
			List<WorkshopProductionCycleBean> deptWorkShopListCopy=new ArrayList<WorkshopProductionCycleBean>(deptWorkShopList);
			//订单采购的信息
			List<PurchaseOrderBean> orderPurchaseList=ordrMaterialPurchaseList.stream().filter(purchase->purchase.getOrderId().equals(orderBean.getOrderId()) && (purchase.getLineNo().equals(orderBean.getRowIndex()) ||purchase.getLineNo().equals("-1") )).collect(Collectors.toList());
			
			//第一次遍历车间，判断物料是否到齐
			for(WorkshopProductionCycleBean workShop:deptWorkShopListCopy) {
				List<String> colorList=new ArrayList<String>();
				//本车间要生产的所有物料
				Set<OrderMaterial> workNeedReportMaterialSet = orderMaterials.stream().filter(
						ma -> workShop.getProcessingObject().indexOf(ma.getMaterialType()) !=-1
						|| workShop.getProcessingObject().indexOf("整架") !=-1
						|| (workShop.getProcessingObject().indexOf("整框") !=-1
								&& kuangList.contains(ma.getMaterialType()))
						|| (workShop.getProcessingObject().indexOf("整腿") !=-1
								&& tuiList.contains(ma.getMaterialType())))
						.collect(Collectors.toSet());
				//如果本车间不需要加工此订单中物料，跳过
				if(workNeedReportMaterialSet.size()<=0) {
					workShop.setMaixStatus(0);
					continue;
				}
			    //找到本车间已经入库的物料
				List<ReportBean> workShopAleradyInMaterial=orderRowReportList.stream().filter(report->report.getWorkShopName().equals(workShop.getId()) && report.getProcedur().equals("交接入库")).collect(Collectors.toList());
				
				//本车间未入库物料
				Set<String> workShopNotInMaterialTypeSet=workNeedReportMaterialSet.stream().map(OrderMaterial::getMaterialType).collect(Collectors.toSet());
				Set<String> workShopAleradyInMaterialTypeSet=workShopAleradyInMaterial.stream().map(ReportBean::getMachining).collect(Collectors.toSet());
				workShopNotInMaterialTypeSet.removeAll(workShopAleradyInMaterialTypeSet);
				Collections.sort(workShopAleradyInMaterial, Comparator.comparing(ReportBean::getTime));
				//遍历比较数量
				for(ReportBean report:workShopAleradyInMaterial) {
				      for(OrderMaterial material:workNeedReportMaterialSet) {
				    	   //如果相同物料的加工数小于订单数,也算物料未到
				    	   if(report.getMachining().equals(material.getMaterialType()) && report.getQualified() < material.getOrderCount()) {
				    		   workShopNotInMaterialTypeSet.add(material.getMaterialType());
				    	   }
                           if(report.getMachining().equals(material.getMaterialType()) && report.getQualified() >=material.getOrderCount()){//如果数量已到齐,设置物料预计完成时间
				    		   StringBuilder stringBuilder=new StringBuilder(workShop.getWorkshopName());
				    		   stringBuilder.append("车间  物料:").append(report.getMachining()).append(" 预计完成时间：")
				    		   .append(TimeAndUnix.timeAddDay(report.getTime(), (int)Math.ceil(workShop.getProcessCycle())));
				    		   colorList.add(stringBuilder.toString());
				    	   }
				      }
				}
				
				
				//如果没有未入库物料，要么以完成, 要么已配料，要么并行车间未到齐
				if(workShopNotInMaterialTypeSet.size()<=0) {
					//判断是否完成
					//如果数量没有不足的，则需判断交接出库是数量是否足够
					boolean finishBool=true;
					List<ReportBean> workShopFinishMaterial=orderRowReportList.stream().filter(report->report.getWorkShopName().equals(workShop.getId()) && (report.getProcedur().equals("交接出库") || report.getProcedur().equals("交接至客户") )).collect(Collectors.toList());
					//出库种类不足,暂时设置为已配料
					if(workShopFinishMaterial.size()<workNeedReportMaterialSet.size()) {
						finishBool=false;
					}
					//种类足的话需判断数量足不足
					for(ReportBean report:workShopFinishMaterial) {
						if(!finishBool) {
							break;
						}
						for(OrderMaterial material:workNeedReportMaterialSet) {
							//如果相同物料的加工数小于订单数，设置,已配料
				    	   if(report.getMachining().equals(material.getMaterialType()) && report.getQualified() < material.getOrderCount()) {
				    		   finishBool=false;
				    		   break;
				    	   }
						}
					} 
					//如果已完成,设置完成跳过循环
					if(finishBool) {
						colorList.clear();
						for(ReportBean report:workShopAleradyInMaterial) {
						   StringBuilder stringBuilder=new StringBuilder(workShop.getWorkshopName());
			    		   stringBuilder.append("车间  物料:").append(report.getMachining()).append("已完成  完成时间:")
			    		   .append(report.getTime().substring(0, 10));
			    		   colorList.add(stringBuilder.toString());
						}
						workShop.setMaixStatus(ReturnStringUtil.MIX_FINISH);
						workShop.setColorList(colorList);
						orderWorkShop.add(workShop.clone());
						continue;
					}else {//如果本车间物料已入库，但是没有生产完成，需要判断并行车间是否到齐
						//获取并行车间生产情况
						boolean bool=true;
						String xx="";
						if(workShopAleradyInMaterial.size()>0) {
							xx=workShopAleradyInMaterial.get(0).getTime();
						}else {
							SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
							xx=simpleDateFormat.format(new Date());
						}
						List<WorkshopProductionCycleBean> sideWorkShopList=deptWorkShopListCopy.stream().filter(work->work.getSort()==workShop.getSort() && !work.getId().equals(workShop.getId())).collect(Collectors.toList());
						//本车间预计完成时间
						String thisFinishTime=TimeAndUnix.timeAddDay(xx, (int)Math.ceil(workShop.getProcessCycle()));
						for(WorkshopProductionCycleBean sideWorkShop:sideWorkShopList) {
							int  pairingType=this.getPairingWorkRresult(sideWorkShop,orderMaterials,kuangList,tuiList,orderRowReportList,deptWorkShopListCopy,orderPurchaseList,colorList,thisFinishTime,companyBean);
							//并行车间有未到料的情况，设置为需等待
							if(pairingType==ReturnStringUtil.NOT_MIX_AND_NOT_ARRIVE) {
								bool=false;
								workShop.setMaixStatus(ReturnStringUtil.MIX_BUT_NEED_WITE);
								break;
							}
						}
						//并行车间全部到齐，设置为已配料
						if(bool) {
							workShop.setMaixStatus(ReturnStringUtil.ALERADY_MIX);
						}
					}//如果本车间物料已入库，但是没有生产完成结束
				}else {//如果有未入库物料
					Set<OrderMaterial> xx=workNeedReportMaterialSet.stream().filter(ma->workShopNotInMaterialTypeSet.contains(ma.getMaterialType())).collect(Collectors.toSet());
					String time=this.checkMaterialLastWorShop(xx,deptWorkShopListCopy,tuiList,kuangList,workShop,orderPurchaseList,orderRowReportList,colorList);
					//如果有一个物料没到齐
					if("".equals(time)) {
						workShop.setMaixStatus(ReturnStringUtil.NOT_MIX_AND_NOT_ARRIVE);
					}else {//如果没有物料没到齐
						//获取并行车间生产情况
						boolean bool=true;
						String xxx="";
						if(workShopAleradyInMaterial.size()>0) {
							xxx=workShopAleradyInMaterial.get(0).getTime();
						}else {
							SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
							xxx=simpleDateFormat.format(new Date());
						}
						List<WorkshopProductionCycleBean> sideWorkShopList=deptWorkShopListCopy.stream().filter(work->work.getSort()==workShop.getSort() && !work.getId().equals(workShop.getId())).collect(Collectors.toList());
						String thisFinishTime=TimeAndUnix.timeAddDay(xxx, (int)Math.ceil(workShop.getProcessCycle()));
						for(WorkshopProductionCycleBean sideWorkShop:sideWorkShopList) {
							int  pairingType=this.getPairingWorkRresult(sideWorkShop,orderMaterials,kuangList,tuiList,orderRowReportList,deptWorkShopListCopy,orderPurchaseList,colorList,thisFinishTime,companyBean);
							//并行车间有未到料的情况，设置为需等待
							if(pairingType==ReturnStringUtil.NOT_MIX_AND_NOT_ARRIVE) {
								bool=false;
								workShop.setMaixStatus(ReturnStringUtil.MIX_BUT_NEED_WITE);
								break;
							}
						}
						//并行车间全部到齐，设置为已配料
						if(bool) {
							workShop.setMaixStatus(ReturnStringUtil.ALERADY_MIX);
						}
					}
				}//如果有未入库物料结束
				workShop.setColorList(colorList);
				orderWorkShop.add(workShop.clone());
			}//第一次遍历车间结束
			Collections.sort(orderWorkShop, Comparator.comparing(WorkshopProductionCycleBean::getSort));
			orderBean.setWpcbList(orderWorkShop);
		}
		dtcpb.setReturnData(orderList);
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		returnMap.put("orderList", dtcpb);
		return returnMap;
	}
	
	/**
	 * 获取并行车间生产状况
	 * @param sideWorkShop (并行车间)
	 * @param orderMaterials (订单物料集合)
	 * @param tuiList (腿集合)
	 * @param kuangList (框集合)
	 * @param orderRowReportList (订单行报工物料)
	 * @param deptWorkShopListCopy (部门车间)
	 * @param orderPurchaseList (订单采购信息)
	 * @param colorLists (明细信息)
	 * @param thisFinishTime (本车间预计完成时间)
	 * @param companyBean 
	 * @return
	 * @throws ParseException 
	 */
	private int getPairingWorkRresult(WorkshopProductionCycleBean sideWorkShop, List<OrderMaterial> orderMaterials, List<String> kuangList, List<String> tuiList, List<ReportBean> orderRowReportList, List<WorkshopProductionCycleBean> deptWorkShopListCopy, List<PurchaseOrderBean> orderPurchaseList, List<String> colorLists, String thisFinishTime, CompanyBean companyBean) throws ParseException {
		List<String> sideColorList=new ArrayList<String>();
	    int retult=0;
		//本车间要生产的所有物料
		Set<OrderMaterial> workNeedReportMaterialSet = orderMaterials.stream().filter(
				ma -> sideWorkShop.getProcessingObject().indexOf(ma.getMaterialType()) !=-1
				|| sideWorkShop.getProcessingObject().indexOf("整架") !=-1
				|| (sideWorkShop.getProcessingObject().indexOf("整框") !=-1
						&& kuangList.contains(ma.getMaterialType()))
				|| (sideWorkShop.getProcessingObject().indexOf("整腿") !=-1
						&& tuiList.contains(ma.getMaterialType())))
				.collect(Collectors.toSet());
		//如果本车间不需要加工此订单中物料，跳过
		if(workNeedReportMaterialSet.size()<=0) {
			return retult;
		}
		 //找到本车间已经入库的物料
		List<ReportBean> workShopAleradyInMaterial=orderRowReportList.stream().filter(report->report.getWorkShopName().equals(sideWorkShop.getId()) && report.getProcedur().equals("交接入库")).collect(Collectors.toList());
        
		//本车间未入库物料
		Set<String> workShopNotInMaterialTypeSet=workNeedReportMaterialSet.stream().map(OrderMaterial::getMaterialType).collect(Collectors.toSet());
		Set<String> workShopAleradyInMaterialTypeSet=workShopAleradyInMaterial.stream().map(ReportBean::getMachining).collect(Collectors.toSet());
		workShopNotInMaterialTypeSet.removeAll(workShopAleradyInMaterialTypeSet);
		Collections.sort(workShopAleradyInMaterial, Comparator.comparing(ReportBean::getTime));
		//遍历比较数量
		for(ReportBean report:workShopAleradyInMaterial) {
		      for(OrderMaterial material:workNeedReportMaterialSet) {
		    	   //如果相同物料的加工数小于订单数,也算物料未到
		    	   if(report.getMachining().equals(material.getMaterialType()) && report.getQualified() < material.getOrderCount()) {
		    		   workShopNotInMaterialTypeSet.add(material.getMaterialType());
		    	   }
                   if(report.getMachining().equals(material.getMaterialType()) && report.getQualified() >= material.getOrderCount())  {//如果数量已到齐,设置物料预计完成时间
		    		   StringBuilder stringBuilder=new StringBuilder(sideWorkShop.getWorkshopName());
		    		   stringBuilder.append("车间  物料:").append(report.getMachining()).append(" 预计完成时间：")
		    		   .append(TimeAndUnix.timeAddDay(report.getTime(), (int)Math.ceil(sideWorkShop.getProcessCycle())));
		    		   sideColorList.add(stringBuilder.toString());
		    	   }
		      }
		}
		
		//如果车间物料全部全部到齐
		if(workShopNotInMaterialTypeSet.size()<=0) {
			//判断是否完成
			//如果数量没有不足的，则需判断交接出库是数量是否足够
			boolean finishBool=true;
			List<ReportBean> workShopFinishMaterial=orderRowReportList.stream().filter(report->report.getWorkShopName().equals(sideWorkShop.getId()) && (report.getProcedur().equals("交接出库") || report.getProcedur().equals("交接至客户") )).collect(Collectors.toList());
			//出库种类不足,暂时设置为已配料
			if(workShopFinishMaterial.size()<workNeedReportMaterialSet.size()) {
				finishBool=false;
			}
			//种类足的话需判断数量足不足
			for(ReportBean report:workShopFinishMaterial) {
				if(!finishBool) {
					break;
				}
				for(OrderMaterial material:workNeedReportMaterialSet) {
					//如果相同物料的加工数小于订单数，设置,已配料
		    	   if(report.getMachining().equals(material.getMaterialType()) && report.getQualified() < material.getOrderCount()) {
		    		   finishBool=false;
		    		   break;
		    	   }
				}
			} 
			//如果已完成,设置完成跳过循环
			if(finishBool) {
				sideColorList.clear();
				for(ReportBean report:workShopAleradyInMaterial) {
				   StringBuilder stringBuilder=new StringBuilder(sideWorkShop.getWorkshopName());
	    		   stringBuilder.append("车间  物料:").append(report.getMachining()).append("已完成  完成时间:")
	    		   .append(report.getTime().substring(0, 10));
	    		   sideColorList.add(stringBuilder.toString());
				}
				retult=ReturnStringUtil.MIX_FINISH;
				
			}else {//如果不是已完成，看时间是否足够
				//本车间预计完成时间
				String xxx="";
				if(workShopAleradyInMaterial.size()>0) {
					xxx=workShopAleradyInMaterial.get(0).getTime();
				}else {
					SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
					xxx=simpleDateFormat.format(new Date());
				}
				String sideFinishTime=TimeAndUnix.timeAddDay(xxx, (int)Math.ceil(sideWorkShop.getProcessCycle()));
				//判断并行车间最晚完成的物料，和本车间完成时间相隔天数
				int upDay=TimeAndUnix.getDateDays(sideFinishTime, thisFinishTime);
				//如果本车间完成时间比最后物料完成时间要晚超过公司设定的配料时间
				if(upDay>companyBean.getMixdCycle()) {
					retult=ReturnStringUtil.NOT_MIX_AND_NOT_ARRIVE;
				} 
			}
		}else {//如果物料没有到期，需判断每个物料到齐情况
			Set<OrderMaterial> xx=workNeedReportMaterialSet.stream().filter(ma->workShopNotInMaterialTypeSet.contains(ma.getMaterialType())).collect(Collectors.toSet());
			String time=this.checkMaterialLastWorShop(xx,deptWorkShopListCopy,tuiList,kuangList,sideWorkShop,orderPurchaseList,orderRowReportList,sideColorList);
		    if("".equals(time)) {
		    	retult=ReturnStringUtil.NOT_MIX_AND_NOT_ARRIVE;
		    }else {
		    	int upDay=TimeAndUnix.getDateDays(time, thisFinishTime);
				//如果本车间完成时间比最后物料完成时间要晚超过公司设定的配料时间
				if(upDay>companyBean.getMixdCycle()) {
					retult=ReturnStringUtil.NOT_MIX_AND_NOT_ARRIVE;
				} 
		    }
		}
		colorLists.addAll(sideColorList);
		return retult;
	}
	
	/**
	 * 校验物料在上一个车间生产情况
	 * @param deptWorkShopListCopy (部门车间)
	 * @param kuangList (框物料集合)
	 * @param tuiList (腿物料集合)
	 * @param sideWorkShop (本车间)
	 * @param orderPurchaseList (订单采购信息)
	 * @param orderRowReportList 
	 * @param sideColorList (明细提示)
	 * @param workShopNotInMaterialTypeSet(车间未到物料集合)
	 * @return
	 * @throws ParseException 
	 */
	private String checkMaterialLastWorShop(Set<OrderMaterial> workShopNotInMaterialTypeSet, List<WorkshopProductionCycleBean> deptWorkShopListCopy, List<String> tuiList, List<String> kuangList, WorkshopProductionCycleBean sideWorkShop, List<PurchaseOrderBean> orderPurchaseList, List<ReportBean> orderRowReportList, List<String> sideColorList) throws ParseException {
		int result=0;
		List<String> finishTimeList=new ArrayList<String>();
		for(OrderMaterial material:workShopNotInMaterialTypeSet) {
			String materialType=material.getMaterialType();
			boolean tuiBool=tuiList.contains(materialType);
			boolean kuangBool=kuangList.contains(materialType);
			//该物料要经过的车间(在本车间之前)
			List<WorkshopProductionCycleBean> materialPassWorkShop=deptWorkShopListCopy.stream().filter(work->work.getSort() <sideWorkShop.getSort() && (work.getProcessingObject().indexOf("整架")!=-1 || work.getProcessingObject().indexOf(materialType)!=-1) ||(materialType.indexOf("整腿")!=-1 && tuiBool) ||(materialType.indexOf("整框")!=-1 && kuangBool)).collect(Collectors.toList());
		    //如果没有,要判断采购
			if(materialPassWorkShop.size()<=0) {
				//物料类型采购情况
				List<PurchaseOrderBean> list=orderPurchaseList.stream().filter(pur->pur.getMaterialType().equals(materialType)).collect(Collectors.toList());
			    //如果没有采购
				if(list.size()<=0) {
					StringBuilder sBuilder =new StringBuilder(sideWorkShop.getWorkshopName());
					sBuilder.append("车间  物料:").append(materialType).append("未采购");
					sideColorList.add(sBuilder.toString());
					result=ReturnStringUtil.NOT_MIX_AND_NOT_ARRIVE;
			    }else {//有采购
			    	PurchaseOrderBean ppBean=list.get(0);
			    	//入库数足够
			    	if(ppBean.getInCount()>=ppBean.getPurchaseCount()) {
			    		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
			    		StringBuilder sBuilder =new StringBuilder(sideWorkShop.getWorkshopName());
						sBuilder.append("车间  物料:").append(materialType).append("已入库  预计完成时间").append(TimeAndUnix.timeAddDay(simpleDateFormat.format(new Date()), (int)Math.ceil(sideWorkShop.getProcessCycle())));
						sideColorList.add(sBuilder.toString());
						finishTimeList.add(TimeAndUnix.timeAddDay(simpleDateFormat.format(new Date()), (int)Math.ceil(sideWorkShop.getProcessCycle())));
			    	}else {//只要采购不完全，就不能生产
			    		StringBuilder sBuilder =new StringBuilder(sideWorkShop.getWorkshopName());
						sBuilder.append("车间  物料:").append(materialType).append("已采购  复期:").append(ppBean.getLaterPhaseOne());
						sideColorList.add(sBuilder.toString());
						result=ReturnStringUtil.NOT_MIX_AND_NOT_ARRIVE;
			    	}
			    }
			}else {//有要经过的车间，需要判断最后一个车间是否完成
				Collections.sort(materialPassWorkShop, Comparator.comparing(WorkshopProductionCycleBean::getSort).reversed());
				WorkshopProductionCycleBean wwBean=materialPassWorkShop.get(0);
				List<ReportBean> list=orderRowReportList.stream().filter(report->report.getMachining().equals(materialType) && report.getWorkShopName().equals(wwBean.getId()) && (report.getProcedur().equals("交接出库") || report.getProcedur().equals("交接至客户")) && report.getQualified()>=material.getOrderCount()).collect(Collectors.toList());
			    //如果没有 
				if(list.size()<=0) {
		    		StringBuilder sBuilder =new StringBuilder(sideWorkShop.getWorkshopName());
					sBuilder.append("车间  物料:").append(materialType).append(" 在上一车间:").append(wwBean.getWorkshopName()).append("未生产完成");
					sideColorList.add(sBuilder.toString());
			    	result=ReturnStringUtil.NOT_MIX_AND_NOT_ARRIVE;
			    }else {
			    	SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
			    	StringBuilder sBuilder =new StringBuilder(sideWorkShop.getWorkshopName());
					sBuilder.append("车间  物料:").append(materialType).append(" 在上一车间:").append(wwBean.getWorkshopName()).append("生产完成  预计完成时间:").append(TimeAndUnix.timeAddDay(simpleDateFormat.format(new Date()), (int)Math.ceil(sideWorkShop.getProcessCycle())));
					sideColorList.add(sBuilder.toString());
					finishTimeList.add(TimeAndUnix.timeAddDay(simpleDateFormat.format(new Date()), (int)Math.ceil(sideWorkShop.getProcessCycle())));
//			    	result=ReturnStringUtil.NOT_MIX_AND_NOT_ARRIVE;
			    }
			}
		}
		if(result==ReturnStringUtil.NOT_MIX_AND_NOT_ARRIVE || finishTimeList.size()<=0)  {
			return "";
		}else {
			Collections.sort(finishTimeList);
			return finishTimeList.get(finishTimeList.size()-1);
		}
	}
//	public Map getOrderMixMaterial(Map map) throws ParseException {
//		
//		Map returnMap = new HashMap<>();
//		int count = 0;
//		// 忽略时间
//		map = this.setOrderMainMapParam(map);
//		map.put("queryOrderPageDateil", 1);
//		DatatablesViewPageBean<OrderBean> dtcpb = new DatatablesViewPageBean<OrderBean>();
//		/**
//		 * 获取整报物料
//		 */
//		List<MaterialTreeBean> materialTreeBeans = structureTreeService.getCompanyMaterialTree(map);
//		// 属于整框的物料
//		List<String> kuangList = materialTreeBeans.stream().filter(material -> material.getType() == 2)
//				.collect(Collectors.toList()).stream().map(MaterialTreeBean::getMaterialType)
//				.collect(Collectors.toList());
//		// 属于整腿的物料
//		List<String> tuiList = materialTreeBeans.stream().filter(material -> material.getType() == 3)
//				.collect(Collectors.toList()).stream().map(MaterialTreeBean::getMaterialType)
//				.collect(Collectors.toList());
//		/**
//		 * 返回主信息
//		 */
//		// 获取查询的订单基本信息
//		List<OrderBean> orderList = orderMapper.queryOrderPageDateil(map);
//		
//		//获取订单采购详情
//		List<PurchaseOrderBean> ordrMaterialPurchaseList=orderMapper.getOrdrMaterialPurchase(orderList);
//		// 获取此条件下的订单那总条数
//		count = orderMapper.queryOrderPageDateilCount(map);
//		/**
//		 *  订单样式五的物料
//		 */
//		List<OrderMaterial> styleFive=orderMapper.getOrderStyleFiveMaterial(orderList);
//		/**
//		 * 订单物料报工情况
//		 */
//		List<ReportBean> reportList=orderMapper.getOrderReportDeatilUserMixByOrderList(orderList);
//		/*
//		 * 获取公司配置
//		 */
//		CompanyBean companyBean=compangMapper.getCompany(map);
//		
//		//部门对应的车间物料map
//		Map<String, List<WorkshopProductionCycleBean>> deptWorkShopMap=new HashMap<String,List<WorkshopProductionCycleBean>>();
//		//部门车间集合
//		List<WorkshopProductionCycleBean> deptWorkShopList=null;
//		for(OrderBean orderBean:orderList) {
//			Set<String> aleradyCompareMaterial=new HashSet<>();
//			//已经获取过部门下的车间
//			if(deptWorkShopMap.containsKey(orderBean.getDeptId())) {
//				deptWorkShopList=deptWorkShopMap.get(orderBean.getDeptId());
//			}else {
//				map.put("deptId", orderBean.getDeptId());
//				deptWorkShopList=basicDataMapper.getDeptNoMegerWorkShop(map);
//				deptWorkShopMap.put(orderBean.getDeptId(), deptWorkShopList);
//			}
//			// 订单中所有要配料的物料
//			List<OrderMaterial> orderMaterials=orderBean.getOrderMaterialList();
//			//加上样式五(行号为-1)的物料
//			orderMaterials.addAll(styleFive.stream().filter(five-> five.getOrderId().equals(orderBean.getOrderId())).collect(Collectors.toList()));
//			// 查询本订单行是否报工
//			List<ReportBean> orderRowReportList=reportList.stream().filter(report->report.getOrderId().equals(orderBean.getOrderId()) && (report.getRowIndex().equals(orderBean.getRowIndex().toString()) || "-1".equals(report.getRowIndex())) && !"款".equals(report.getMachining())).collect(Collectors.toList());
//			//降序排序
//			Collections.sort(deptWorkShopList, Comparator.comparing(WorkshopProductionCycleBean::getSort).reversed());
//			//订单车间结果汇总
////			List<WorkshopProductionCycleBean> orderWorkShop=new ArrayList<WorkshopProductionCycleBean>();
//			
//			List<WorkshopProductionCycleBean> deptWorkShopListCopy=new ArrayList<WorkshopProductionCycleBean>(deptWorkShopList);
//			
//			//第一次遍历车间，判断物料是否到齐
//			for(WorkshopProductionCycleBean workShop:deptWorkShopListCopy) {
//				
//				//本车间要生产的所有物料
//				Set<OrderMaterial> workNeedReportMaterialSet = orderMaterials.stream().filter(
//						ma -> workShop.getProcessingObject().indexOf(ma.getMaterialType()) !=-1
//						|| workShop.getProcessingObject().indexOf("整架") !=-1
//						|| (workShop.getProcessingObject().indexOf("整框") !=-1
//						&& kuangList.contains(ma.getMaterialType()))
//						|| (workShop.getProcessingObject().indexOf("整腿") !=-1
//						&& tuiList.contains(ma.getMaterialType())))
//						.collect(Collectors.toSet());
//				//如果本车间不需要加工此订单中物料，跳过
//				if(workNeedReportMaterialSet.size()<=0) {
//					workShop.setMaixStatus(0);
//					continue;
//				}
//				//找到本车间已经入库的物料
//				List<ReportBean> workShopAleradyInMaterial=orderRowReportList.stream().filter(report->report.getWorkShopName().equals(workShop.getId()) && report.getProcedur().equals("交接入库")).collect(Collectors.toList());
//				
//				//本车间未入库物料
//				Set<String> workShopNotInMaterialTypeSet=workNeedReportMaterialSet.stream().map(OrderMaterial::getMaterialType).collect(Collectors.toSet());
//				Set<String> workShopAleradyInMaterialTypeSet=workShopAleradyInMaterial.stream().map(ReportBean::getMachining).collect(Collectors.toSet());
//				workShopNotInMaterialTypeSet.removeAll(workShopAleradyInMaterialTypeSet);
//				
//				//还没有入库的物料类型
//				
//				//如果车间入库物料数没有应该生生产数多，设置为未到齐加不配料
//				if(workShopAleradyInMaterial.size()<workNeedReportMaterialSet.size()) {
//					workShop.setMaixStatus(ReturnStringUtil.NOT_MIX_AND_NOT_ARRIVE);//未到齐加不配套
//					continue;
//				}
//				//遍历比较数量
//				for(ReportBean report:workShopAleradyInMaterial) {
//					for(OrderMaterial material:workNeedReportMaterialSet) {
//						//如果相同物料的加工数小于订单数，设置,未配料
//						if(report.getMachining().equals(material.getMaterialType()) && report.getQualified() < material.getOrderCount()) {
//							workShop.setMaixStatus(ReturnStringUtil.NOT_MIX_AND_NOT_ARRIVE);//未到齐加不配套
//							break;
//						}
//					}
//				}
//				//如果有数量不足的，跳出循环
//				if(workShop.getMaixStatus()==ReturnStringUtil.NOT_MIX_AND_NOT_ARRIVE) {
//					continue;
//				}
//				
//				//如果数量没有不足的，则需判断交接出库是数量是否足够
//				List<ReportBean> workShopFinishMaterial=orderRowReportList.stream().filter(report->report.getWorkShopName().equals(workShop.getId()) && (report.getProcedur().equals("交接出库") || report.getProcedur().equals("交接至客户") )).collect(Collectors.toList());
//				//出库种类不足,暂时设置为已配料
//				if(workShopFinishMaterial.size()<workNeedReportMaterialSet.size()) {
//					workShop.setMaixStatus(ReturnStringUtil.ALERADY_MIX);
//					continue;
//				}
//				//种类足的话需判断数量足不足
//				for(ReportBean report:workShopFinishMaterial) {
//					for(OrderMaterial material:workNeedReportMaterialSet) {
//						//如果相同物料的加工数小于订单数，设置,已配料
//						if(report.getMachining().equals(material.getMaterialType()) && report.getQualified() < material.getOrderCount()) {
//							workShop.setMaixStatus(ReturnStringUtil.ALERADY_MIX);//未到齐加不配套
//							break;
//						}
//					}
//				}
//				//如果有出库数量不足的物料的话
//				if(workShop.getMaixStatus()==ReturnStringUtil.ALERADY_MIX) {
//					continue;
//				}
//				//否则设置完成
//				workShop.setMaixStatus(ReturnStringUtil.MIX_FINISH);
//			}//第一次遍历车间结束
//			
//			//第二次遍历车间，判断一配料的车间并行车间生产情况
//			for(WorkshopProductionCycleBean workShop:deptWorkShopListCopy) {
//				List<String> colorList=new ArrayList<String>();
//				//如果车间是已完成状态
//				if(workShop.getMaixStatus()==ReturnStringUtil.MIX_FINISH) {
//					List<ReportBean> workShopAleradyInMaterial=orderRowReportList.stream().filter(report->report.getWorkShopName().equals(workShop.getId()) && (report.getProcedur().equals("交接出库") || report.getProcedur().equals("交接至客户"))).collect(Collectors.toList());
//					Collections.sort(workShopAleradyInMaterial, Comparator.comparing(ReportBean::getTime));
//					//设置点击查看详情信息
//					for(ReportBean report:workShopAleradyInMaterial) {
//						StringBuilder sb=new StringBuilder();
//						sb.append(" 已出物料:").append(report.getMachining())
//						.append(" 出库时间:").append(report.getTime()).append(" 出库数量:").append(report.getQualified());
//						colorList.add(sb.toString());
//					}
//				}
//				
//				//如果车间是物料未到齐状态
//				if(workShop.getMaixStatus()==ReturnStringUtil.NOT_MIX_AND_NOT_ARRIVE) {
//					List<ReportBean> workShopAleradyInMaterial=orderRowReportList.stream().filter(report->report.getWorkShopName().equals(workShop.getId()) &&  report.getProcedur().equals("交接入库")).collect(Collectors.toList());
//					Collections.sort(workShopAleradyInMaterial, Comparator.comparing(ReportBean::getTime));
//					//设置点击查看详情信息
//					for(ReportBean report:workShopAleradyInMaterial) {
//						StringBuilder sb=new StringBuilder();
//						sb.append("已入物料:").append(report.getMachining())
//						.append(" 入库时间:").append(report.getTime()).append(" 入库数量:").append(report.getQualified());
//						colorList.add(sb.toString());
//					}
//					Set<String> aleradyMaterial=workShopAleradyInMaterial.stream().map(ReportBean::getMachining).collect(Collectors.toSet());
//					Set<OrderMaterial> workNoReportMaterialSet = orderMaterials.stream().filter(
//							ma -> !aleradyMaterial.contains(ma.getMaterialType()) && (workShop.getProcessingObject().indexOf(ma.getMaterialType()) !=-1
//							|| workShop.getProcessingObject().indexOf("整架") !=-1
//							|| (workShop.getProcessingObject().indexOf("整框") !=-1
//							&& kuangList.contains(ma.getMaterialType()))
//							|| (workShop.getProcessingObject().indexOf("整腿") !=-1
//							&& tuiList.contains(ma.getMaterialType()))) )
//							.collect(Collectors.toSet());
//					//遍历该物料，找到此物料到此车间生产完成的日期
//					for(OrderMaterial material:workNoReportMaterialSet) {
//						StringBuilder sb=new StringBuilder("未入物料:");
//						sb.append(material.getMaterialType());
//						//此物料已经入库的车间
//						List<ReportBean> materialReportList=orderRowReportList.stream().filter(report-> report.getProcedur().equals("交接入库") && report.getMachining().equals(material.getMaterialType())).collect(Collectors.toList());
//						//此物料有报过工
//						if(materialReportList.size()>0) {
//							Collections.sort(materialReportList, Comparator.comparing(ReportBean::getTime).reversed());
//							double sumDay=0.0;
//							ReportBean reportBean=materialReportList.get(0);
//							sb.append(reportBean.getTime());
//							sb.append("入库车间:").append(reportBean.getWorkShopId());
//							boolean tuiBool=tuiList.contains(material.getMaterialType());
//							boolean kuangBool=kuangList.contains(material.getMaterialType());
//							//该物料要经过的车间
//							List<WorkshopProductionCycleBean> materialPassWorkShop=deptWorkShopListCopy.stream().filter(work->work.getSort() >=reportBean.getSort() && work.getSort()<=workShop.getSort() && (work.getProcessingObject().indexOf("整架")!=-1 || work.getProcessingObject().indexOf(material.getMaterialType())!=-1) ||(work.getProcessingObject().indexOf("整腿")!=-1 && tuiBool) ||(work.getProcessingObject().indexOf("整框")!=-1 && kuangBool)).collect(Collectors.toList());
//							for(WorkshopProductionCycleBean work:materialPassWorkShop) {
//								sumDay=sumDay+work.getProcessCycle();
//							}
//							sb.append(" 本车间预计完成时间:").append(TimeAndUnix.timeAddDay(reportBean.getTime(), (int)Math.ceil(sumDay)));
//						}else {//如果此物料没有报过工
//							SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
//							double sumDay=0.0;
//							boolean tuiBool=tuiList.contains(material.getMaterialType());
//							boolean kuangBool=kuangList.contains(material.getMaterialType());
//							//该物料要经过的车间
//							List<WorkshopProductionCycleBean> materialPassWorkShop=deptWorkShopListCopy.stream().filter(work-> work.getSort()<=workShop.getSort() && (work.getProcessingObject().indexOf("整架")!=-1 || work.getProcessingObject().indexOf(material.getMaterialType())!=-1) ||(work.getProcessingObject().indexOf("整腿")!=-1 && tuiBool) ||(work.getProcessingObject().indexOf("整框")!=-1 && kuangBool)).collect(Collectors.toList());
//							for(WorkshopProductionCycleBean work:materialPassWorkShop) {
//								sumDay=sumDay+work.getProcessCycle();
//							}
//							sumDay=sumDay+material.getProcurementCycles();
//							sb.append("未生产,本车间预计完成时间").append(TimeAndUnix.timeAddDay(simpleDateFormat.format(new Date()), (int)Math.ceil(sumDay)));
//							colorList.add(sb.toString());
//						} 
//					}//遍历物料结束
//				}
//				//如果是已配料状态，需比对并行车间状况
//				if(workShop.getMaixStatus()==ReturnStringUtil.ALERADY_MIX) {
//					//本车间最晚完成的物料为，最晚入库的物料+本车间流程周期
//					//找到本车间已经入库的物料
//					List<ReportBean> workShopAleradyInMaterial=orderRowReportList.stream().filter(report->report.getWorkShopName().equals(workShop.getId()) && report.getProcedur().equals("交接入库")).collect(Collectors.toList());
//					Collections.sort(workShopAleradyInMaterial, Comparator.comparing(ReportBean::getTime));
//					String thisWorkFinishTimeStr=TimeAndUnix.timeAddDay(workShopAleradyInMaterial.get(workShopAleradyInMaterial.size()-1).getTime(), (int)Math.ceil(workShop.getProcessCycle()));
//					List<String> timeSet=new ArrayList<String>();
//					timeSet.add(thisWorkFinishTimeStr);
//					//设置点击查看详情信息
//					for(ReportBean report:workShopAleradyInMaterial) {
//						StringBuilder sb=new StringBuilder("本车间:");
//						sb.append(workShop.getWorkshopName()).append(" 物料类型:").append(report.getMachining())
//						.append(" 入库时间:").append(report.getTime()).append(" 入库数量:").append(report.getQualified());
//						colorList.add(sb.toString());
//					}
//					colorList.add("本车间预计完成时间："+thisWorkFinishTimeStr);
//					
//					
//					//并行车间(不包含本车间)
//					List<WorkshopProductionCycleBean> sideWorkShopList=deptWorkShopListCopy.stream().filter(work->work.getSort()==workShop.getSort() && !work.getId().equals(workShop.getId())).collect(Collectors.toList());
//					//如果有并行车间，需找到每个车间最晚生产完成的时间
//					if(sideWorkShopList.size()>0) {
//						for(WorkshopProductionCycleBean sideWorkShop:sideWorkShopList) {
//							//并行车间入库物料
//							List<ReportBean> sideWorkShopAleradyInMaterial=orderRowReportList.stream().filter(report->report.getWorkShopName().equals(sideWorkShop.getId()) && report.getProcedur().equals("交接入库")).collect(Collectors.toList());
//							//如果车间是已经配料的话,取最后一个入库车间的时间加车间周期
//							if(sideWorkShop.getMaixStatus()==ReturnStringUtil.ALERADY_MIX) {
//								Collections.sort(sideWorkShopAleradyInMaterial, Comparator.comparing(ReportBean::getTime));
//								String sideTime=TimeAndUnix.timeAddDay(sideWorkShopAleradyInMaterial.get(0).getTime(), (int)Math.ceil(sideWorkShop.getProcessCycle()));
//								colorList.add("并行车间"+sideWorkShop.getWorkshopName()+"物料已到齐,预计完成时间:"+sideTime);
//								timeSet.add(sideTime);
//							}
//							if(sideWorkShop.getMaixStatus()==ReturnStringUtil.NOT_MIX_AND_NOT_ARRIVE) {
//								List<String> sideTimeSet=new ArrayList<String>();
//								Set<String> aleradyMaterial=sideWorkShopAleradyInMaterial.stream().map(ReportBean::getMachining).collect(Collectors.toSet());
//								//本车间未到的物料
//								Set<OrderMaterial> workNoReportMaterialSet = orderMaterials.stream().filter(
//										ma -> !aleradyMaterial.contains(ma.getMaterialType()) && (sideWorkShop.getProcessingObject().indexOf(ma.getMaterialType()) !=-1
//										|| sideWorkShop.getProcessingObject().indexOf("整架") !=-1
//										|| (sideWorkShop.getProcessingObject().indexOf("整框") !=-1
//										&& kuangList.contains(ma.getMaterialType()))
//										|| (sideWorkShop.getProcessingObject().indexOf("整腿") !=-1
//										&& tuiList.contains(ma.getMaterialType()))) )
//										.collect(Collectors.toSet());
//								//遍历该物料，找到此物料到此车间生产完成的日期
//								for(OrderMaterial material:workNoReportMaterialSet) {
//									//此物料已经入库的车间
//									List<ReportBean> materialReportList=orderRowReportList.stream().filter(report-> report.getProcedur().equals("交接入库") && report.getMachining().equals(material.getMaterialType())).collect(Collectors.toList());
//									//此物料有报过工
//									if(materialReportList.size()>0) {
//										Collections.sort(materialReportList, Comparator.comparing(ReportBean::getTime).reversed());
//										double sumDay=0.0;
//										ReportBean reportBean=materialReportList.get(0);
//										boolean tuiBool=tuiList.contains(material.getMaterialType());
//										boolean kuangBool=kuangList.contains(material.getMaterialType());
//										//该物料要经过的车间
//										List<WorkshopProductionCycleBean> materialPassWorkShop=deptWorkShopListCopy.stream().filter(work->work.getSort() >=reportBean.getSort() && work.getSort()<=sideWorkShop.getSort() && (work.getProcessingObject().indexOf("整架")!=-1 || work.getProcessingObject().indexOf(material.getMaterialType())!=-1) ||(work.getProcessingObject().indexOf("整腿")!=-1 && tuiBool) ||(work.getProcessingObject().indexOf("整框")!=-1 && kuangBool)).collect(Collectors.toList());
//										for(WorkshopProductionCycleBean work:materialPassWorkShop) {
//											sumDay=sumDay+work.getProcessCycle();
//										}
//										sideTimeSet.add(TimeAndUnix.timeAddDay(reportBean.getTime(), (int)Math.ceil(sumDay)));
//										timeSet.add(TimeAndUnix.timeAddDay(reportBean.getTime(), (int)Math.ceil(sumDay)));
//									}else {//如果此物料没有报过工
//										SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
//										double sumDay=0.0;
//										boolean tuiBool=tuiList.contains(material.getMaterialType());
//										boolean kuangBool=kuangList.contains(material.getMaterialType());
//										//该物料要经过的车间
//										List<WorkshopProductionCycleBean> materialPassWorkShop=deptWorkShopListCopy.stream().filter(work-> work.getSort()<=sideWorkShop.getSort() && (work.getProcessingObject().indexOf("整架")!=-1 || work.getProcessingObject().indexOf(material.getMaterialType())!=-1) ||(work.getProcessingObject().indexOf("整腿")!=-1 && tuiBool) ||(work.getProcessingObject().indexOf("整框")!=-1 && kuangBool)).collect(Collectors.toList());
//										for(WorkshopProductionCycleBean work:materialPassWorkShop) {
//											sumDay=sumDay+work.getProcessCycle();
//										}
//										sumDay=sumDay+material.getProcurementCycles();
//										timeSet.add(TimeAndUnix.timeAddDay(simpleDateFormat.format(new Date()), (int)Math.ceil(sumDay)));
//										sideTimeSet.add(TimeAndUnix.timeAddDay(simpleDateFormat.format(new Date()), (int)Math.ceil(sumDay)));
//									}
//									
//								}//遍历物料结束
//								Collections.sort(sideTimeSet);
//								colorList.add("并行车间"+sideWorkShop.getWorkshopName()+"物料未到齐,预计完成时间:"+sideTimeSet.get(sideTimeSet.size()-1));
//							}//判断是否有物料未到达
//						}//遍历并行车间结束
//					}//判断是否有并行车间
//					Collections.sort(timeSet);
//					String lastFinishTime=timeSet.get(timeSet.size()-1);
//					//判断并行车间最晚完成的物料，和本车间完成时间相隔天数
//					int upDay=TimeAndUnix.getDateDays(lastFinishTime, thisWorkFinishTimeStr);
//					//如果本车间完成时间比最后物料完成时间要晚超过公司设定的配料时间
//					if(upDay>companyBean.getMixdCycle()) {
//						workShop.setMaixStatus(ReturnStringUtil.MIX_BUT_NEED_WITE);
//					}
//				}
//				workShop.setColorList(colorList);
//			}
//			Collections.sort(deptWorkShopListCopy, Comparator.comparing(WorkshopProductionCycleBean::getSort));
//			orderBean.setWpcbList(deptWorkShopListCopy);
//		}
//		dtcpb.setReturnData(orderList);
//		dtcpb.setiTotalDisplayRecords(count);
//		dtcpb.setiTotalRecords(count);
//		returnMap.put("orderList", dtcpb);
//		return returnMap;
//	}



	/**
	 * 校验订单是否完成
	 * @param orderId(订单编号)
	 */
	public void checkOrderIsFinish(String orderId) {
		OrderBean orderBean=this.getOrderByOrderId(orderId);
		Assert.notNull(orderBean,"该订单不存在");
		Assert.isTrue(orderBean.getSort()>=0,orderId+"订单已完成,不可操作");
	}

	/**
	 * 获取订单类型接口
	 * @param map
	 * @return
	 */
	public List<String> getOrderType(Map map) {
		return orderMapper.getOrderType(map);
	}

	/**
	 * 获取公司订单编号（用于设备换单）
	 * @param map
	 * @return
	 */
	public List<OrderBean> getCompanyOrder(Map map) {
		List<OrderBean> list=orderMapper.getCompanyOrder(map);
		return list;
	}

	/**
	 * 获取订单配套情况
	 * @param map
	 * @return
	 * @throws CloneNotSupportedException 
	 * @throws ParseException 
	 */
	
   public   List<Map> getOrderMatchingDetailFromRedis(Map map)  throws ParseException, CloneNotSupportedException {
	   Map<String, List<Map>> data = (Map<String, List<Map>>) RedisCache.getDataFromRedis(RedisKey.ORDER_MATCHING_DETAIL);
//	   Map<String, List<Map>> data =null;
	   List<Map> returnList = null;
	   if(data==null) {
		   returnList = this.getOrderMatchingDetail(map);
	   }else {
		 returnList= data.get(map.get("loginCompany").toString());
		 if(returnList == null) {
			 returnList = this.getOrderMatchingDetail(map);
		 }
	   }
	   return returnList;
   }
    
   /**
    * 配套定时器
    */
   public void  orderMatchingDetailScheduleMethod() {
	   Map<String, List<Map>> data = (Map<String, List<Map>>) RedisCache.getDataFromRedis(RedisKey.ORDER_MATCHING_DETAIL);
	   for(String company:data.keySet()) {
		   try {
			   Map map = new HashMap();
			   map.put("loginCompany", company);
			   this.getOrderMatchingDetail(map);
		   }catch(Exception e) {
			   data.put(company, null);
		   }
	   }
   }
	
	public List<Map> getOrderMatchingDetail(Map map) throws ParseException, CloneNotSupportedException {
		map.put("isSetOrder", -3);
		map.put("companyOrderId", "");
		map.put("factoryId", "");
		map.put("customer", "");
		map.put("customerId", "");
		map.put("deptId", "");
		DatatablesViewPageBean<OrderBean> datatablesViewPageBean= (DatatablesViewPageBean<OrderBean>) this.getOrderMixMaterial(map).get("orderList");
		List<OrderBean> list = datatablesViewPageBean.getReturnData();
		Map<String, List<OrderBean>> oneOrderMap =list.stream().collect(Collectors.groupingBy(OrderBean::getOrderId));
//		//订单主信息 
		List<Map> returnList = new ArrayList<Map>();
		List<OrderMaterial> materialTypeList = orderMapper.getOrderMatchingMain(map);
		Map<String,List<OrderMaterial>> orderMaterialtypeMap =  materialTypeList.stream().collect(Collectors.groupingBy(OrderMaterial::getOrderId));
		for(String orderId:oneOrderMap.keySet()) {
			//设置物料类型
			List<OrderMaterial> oneOrderMaterialTypeList = orderMaterialtypeMap.get(orderId);
			Map onOrderMap = new HashMap();
			onOrderMap.put("orderId", orderId);
			onOrderMap.put("orderMaterialList", oneOrderMaterialTypeList);
			List<OrderBean> oneOrderList = oneOrderMap.get(orderId);
			OrderBean xx=oneOrderList.get(0);
			onOrderMap.put("companyOrderId", xx.getCompanyOrderId());
			onOrderMap.put("factoryId", xx.getFactoryId());
			onOrderMap.put("customerId", xx.getCustomerId());
			onOrderMap.put("customerOrderId", xx.getCustomerOrderId());
			onOrderMap.put("customer", xx.getCustomer());
			onOrderMap.put("orderCount", oneOrderList.stream().mapToInt(OrderBean::getOrderCount).sum());
			onOrderMap.put("feedCount", oneOrderList.stream().mapToInt(OrderBean::getFeedCount).sum());
			onOrderMap.put("jiaoDate", xx.getJiaoDate());
			onOrderMap.put("xiaDanDate", xx.getXiaDanDate());
			onOrderMap.put("feedCount", oneOrderList.stream().mapToInt(OrderBean::getFeedCount).sum());
			onOrderMap.put("deptId", xx.getDeptId());
			onOrderMap.put("deptName", xx.getDeptName());
			//单个订单所有的车间
			List<WorkshopProductionCycleBean> wpcbList = xx.getWpcbList();
			List<Map> wpcbMapList = new ArrayList<Map>();
			//设置主信息一个车间的值
			for(WorkshopProductionCycleBean onWorkShop:wpcbList) {
				Map wcpbMap = new HashMap();
				wcpbMap.put("id", onWorkShop.getId());
				wcpbMap.put("workshopName", onWorkShop.getWorkshopName());
				wcpbMap.put("maixStatus", onWorkShop.getMaixStatus());
				wcpbMap.put("sort", onWorkShop.getSort());
				int mixStatus = 4;
				List<Integer> mixStatusList = new ArrayList<Integer>();
				//遍历每一个车间的值
				for(OrderBean oneDetail:oneOrderList) {
					List<WorkshopProductionCycleBean> ffBeans = oneDetail.getWpcbList();
					//找到同一个车间
					for(WorkshopProductionCycleBean ww:ffBeans) {
						if(onWorkShop.getId().equals(ww.getId())) {
							mixStatusList.add(ww.getMaixStatus());
							break;
						}
					}
				}
				//没有值或者有一个不配套，就不配套
				if(mixStatusList.size()<=0 || mixStatusList.contains(2)) {
					wcpbMap.put("maixStatus", 2);
				}else {
					wcpbMap.put("maixStatus", 4);
				}
				wpcbMapList.add(wcpbMap);
			}
			onOrderMap.put("wpcbList", wpcbMapList);
			returnList.add(onOrderMap);
			List<Map> listMap=this.simplifyDate(oneOrderList);
			onOrderMap.put("detail", listMap);
		}
		Map<String, List<Map>> data = (Map<String, List<Map>>) RedisCache.getDataFromRedis(RedisKey.ORDER_MATCHING_DETAIL);
		if(data == null) {
			data = new HashMap<String, List<Map>>();
		}
		data.put(map.get("loginCompany").toString(), returnList);
		RedisCache.setDataToRedis(RedisKey.ORDER_MATCHING_DETAIL, data, RedisKey.ORDER_MATCHING_DETAIL_TIME);
		return returnList;
	}

	/**
	 * 简化数据
	 * @param oneOrderList
	 * @return
	 */
	private List<Map> simplifyDate(List<OrderBean> oneOrderList) {
		List<Map> reurnList= new ArrayList<Map>();
		for(OrderBean order:oneOrderList) {
			Map cc=  new HashMap();
			cc.put("orderId", order.getOrderId());
			cc.put("feedCount", order.getFeedCount());
			cc.put("orderCount", order.getOrderCount());
			List<Map> setList= new ArrayList<Map>();
			List<WorkshopProductionCycleBean> workList =order.getWpcbList();
			if(workList != null) {
				for(WorkshopProductionCycleBean ww:workList) {
					Map xx = new HashMap();
					xx.put("id", ww.getId());
					xx.put("workshopName", ww.getWorkshopName());
					xx.put("maixStatus", ww.getMaixStatus());
					xx.put("sort", ww.getSort());
					setList.add(xx);
				}
			}
			cc.put("wpcbList", setList);
			reurnList.add(cc);
		}
		return reurnList;
	}
	
}
